초기 커밋.
This commit is contained in:
1353
LFP_Manager_PRM/Utils/csDBUtils.cs
Normal file
1353
LFP_Manager_PRM/Utils/csDBUtils.cs
Normal file
File diff suppressed because it is too large
Load Diff
299
LFP_Manager_PRM/Utils/csExcelControl.cs
Normal file
299
LFP_Manager_PRM/Utils/csExcelControl.cs
Normal file
@@ -0,0 +1,299 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
using System.Data;
|
||||
using System.Data.OleDb;
|
||||
|
||||
namespace LFP_Manager.Utils
|
||||
{
|
||||
class csExcelControl
|
||||
{
|
||||
/// <summary>
|
||||
/// Excel Database Control Class
|
||||
/// version 0.1.5
|
||||
/// </summary>
|
||||
/// <License>
|
||||
/// <Copyright>자유배포</Copyright>
|
||||
/// <Writer>황현우 [ LiA's Blog ]</Writer>
|
||||
/// <DocUrl>http://blog.naver.com/exila</DocUrl>
|
||||
/// <Company>CoreBank Co.,Ltd.</Company>
|
||||
/// <Note>불펌금지효.. 만든 사람의 성의좀 생각을..-_-;;</Note>
|
||||
/// </License>
|
||||
/*---------------------------------------------------------------------
|
||||
* Connection String 에는 어마어마한 옵션들이.. 주로 영문 사이트이긴
|
||||
* 하지만 좀더 상세한 제어를 원한다면 OleDB Connection String 옵션과
|
||||
* Extended Properties 에 들어가는 Excel Option 들을 살펴보는 것이 좋을
|
||||
* 듯.. HDR = 첫줄을 헤더로 사용할 것인지,IMEX = 데이터유형적용여부 등등
|
||||
*-------------------------------------------------------------------*/
|
||||
|
||||
// 확장명 XLS (Excel 97~2003 용)
|
||||
private const string ConnectStrFrm_Excel97_2003 =
|
||||
"Provider=Microsoft.Jet.OLEDB.4.0;" +
|
||||
"Data Source=\"{0}\";" +
|
||||
"Mode=ReadWrite|Share Deny None;" +
|
||||
"Extended Properties='Excel 8.0; HDR={1}; IMEX={2}';" +
|
||||
"Persist Security Info=False";
|
||||
|
||||
// 확장명 XLSX (Excel 2007 이상용)
|
||||
private const string ConnectStrFrm_Excel =
|
||||
"Provider=Microsoft.ACE.OLEDB.12.0;" +
|
||||
"Data Source=\"{0}\";" +
|
||||
"Mode=ReadWrite|Share Deny None;" +
|
||||
"Extended Properties='Excel 12.0; HDR={1}; IMEX={2}';" +
|
||||
"Persist Security Info=False";
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Excel 파일의 형태를 반환한다.
|
||||
/// -2 : Error
|
||||
/// -1 : 엑셀파일아님
|
||||
/// 0 : 97-2003 엑셀 파일 (xls)0
|
||||
/// 1 : 2007 이상 파일 (xlsx)
|
||||
/// </summary>
|
||||
/// <param name="XlsFile">
|
||||
/// Excel File 명 전체 경로입니다.
|
||||
/// </param>
|
||||
public static int ExcelFileType(string XlsFile)
|
||||
{
|
||||
byte[,] ExcelHeader = {
|
||||
{ 0xD0, 0xCF, 0x11, 0xE0, 0xA1 }, // XLS File Header
|
||||
{ 0x50, 0x4B, 0x03, 0x04, 0x14 } // XLSX File Header
|
||||
};
|
||||
|
||||
// result -2 = error, -1 = not excel , 0 = xls , 1 = xlsx
|
||||
int result = -1;
|
||||
FileInfo FI = new FileInfo(XlsFile);
|
||||
FileStream FS = FI.Open(FileMode.Open);
|
||||
|
||||
try
|
||||
{
|
||||
byte[] FH = new byte[5];
|
||||
FS.Read(FH, 0, 5);
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
for (int j = 0; j < 5; j++)
|
||||
{
|
||||
if (FH[j] != ExcelHeader[i, j]) break;
|
||||
else if (j == 4) result = i;
|
||||
}
|
||||
if (result >= 0) break;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
result = (-2);
|
||||
//throw e;
|
||||
}
|
||||
finally
|
||||
{
|
||||
FS.Close();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Excel 파일을 DataSet 으로 변환하여 반환한다.
|
||||
/// </summary>
|
||||
/// <param name="FileName">
|
||||
/// Excel File 명 PullPath
|
||||
/// </param>
|
||||
/// <param name="UseHeader">
|
||||
/// 첫번째 줄을 Field 명으로 사용할 것이지 여부
|
||||
/// </param>
|
||||
private static DataSet OpenExcel(string FileName, bool UseHeader)
|
||||
{
|
||||
DataSet DS = null;
|
||||
|
||||
string[] HDROpt = { "NO", "YES" };
|
||||
string HDR = "";
|
||||
string ConnStr = "";
|
||||
|
||||
if (UseHeader)
|
||||
HDR = HDROpt[1];
|
||||
else
|
||||
HDR = HDROpt[0];
|
||||
|
||||
int ExcelType = ExcelFileType(FileName);
|
||||
switch (ExcelType)
|
||||
{
|
||||
case (-2): throw new Exception(FileName + "의 형식검사중 오류가 발생하였습니다."); // An error occurred during type inspection
|
||||
case (-1): throw new Exception(FileName + "은 엑셀 파일형식이 아닙니다."); // Is not an Excel file format.
|
||||
case ( 0): ConnStr = string.Format(ConnectStrFrm_Excel97_2003, FileName, HDR, "1"); break;
|
||||
case ( 1): ConnStr = string.Format(ConnectStrFrm_Excel, FileName, HDR, "1"); break;
|
||||
}
|
||||
|
||||
OleDbConnection OleDBConn = null;
|
||||
OleDbDataAdapter OleDBAdap = null;
|
||||
DataTable Schema;
|
||||
|
||||
try
|
||||
{
|
||||
OleDBConn = new OleDbConnection(ConnStr);
|
||||
OleDBConn.Open();
|
||||
|
||||
Schema = OleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
|
||||
|
||||
DS = new DataSet();
|
||||
|
||||
foreach (DataRow DR in Schema.Rows)
|
||||
{
|
||||
OleDBAdap = new OleDbDataAdapter(DR["TABLE_NAME"].ToString(), OleDBConn);
|
||||
|
||||
OleDBAdap.SelectCommand.CommandType = CommandType.TableDirect;
|
||||
OleDBAdap.AcceptChangesDuringFill = false;
|
||||
|
||||
string TableName = DR["TABLE_NAME"].ToString().Replace("$", String.Empty).Replace("'", String.Empty);
|
||||
|
||||
if (DR["TABLE_NAME"].ToString().Contains("$")) OleDBAdap.Fill(DS, TableName);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (OleDBConn != null) OleDBConn.Close();
|
||||
}
|
||||
return DS;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DataSet 을 Excel 파일로 저장한다.
|
||||
/// </summary>
|
||||
/// <param name="FileName">
|
||||
/// Excel File 명 PullPath
|
||||
/// </param>
|
||||
/// <param name="DS">
|
||||
/// Excel 로 저장할 대상 DataSet 객체.
|
||||
/// </param>
|
||||
/// <param name="ExistDel">
|
||||
/// 동일한 파일명이 있을 때 삭제 할 것인지 여부, 파일이 있고 false 면 저장안하고 그냥 false 를 리턴.
|
||||
/// </param>
|
||||
/// <param name="OldExcel">
|
||||
/// xls 형태로 저장할 것인지 여부, false 이면 xlsx 형태로 저장함.
|
||||
/// </param>
|
||||
private static bool SaveExcel(string FileName, DataSet DS, bool ExistDel, bool OldExcel)
|
||||
{
|
||||
bool result = true;
|
||||
|
||||
if (File.Exists(FileName))
|
||||
if (ExistDel) File.Delete(FileName);
|
||||
else return result;
|
||||
|
||||
string TempFile = FileName;
|
||||
// 파일 확장자가 xls 이나 xlsx 가 아니면 아예 파일을 안만들어서
|
||||
// 템프파일로 생성후 지정한 파일명으로 변경..
|
||||
|
||||
OleDbConnection OleDBConn = null;
|
||||
|
||||
try
|
||||
{
|
||||
OleDbCommand Cmd = null;
|
||||
string ConnStr = "";
|
||||
|
||||
if (OldExcel)
|
||||
{
|
||||
TempFile = TempFile + ".xls";
|
||||
ConnStr = string.Format(ConnectStrFrm_Excel97_2003, TempFile, "YES", "0");
|
||||
}
|
||||
else
|
||||
{
|
||||
TempFile = TempFile + ".xlsx";
|
||||
ConnStr = string.Format(ConnectStrFrm_Excel, TempFile, "YES", "0");
|
||||
}
|
||||
|
||||
OleDBConn = new OleDbConnection(ConnStr);
|
||||
OleDBConn.Open();
|
||||
|
||||
// Create Table(s).. : 테이블 단위 처리
|
||||
foreach (DataTable DT in DS.Tables)
|
||||
{
|
||||
String TableName = DT.TableName;
|
||||
|
||||
StringBuilder FldsInfo = new StringBuilder();
|
||||
StringBuilder Flds = new StringBuilder();
|
||||
|
||||
// Create Field(s) String : 현재 테이블의 Field 명 생성
|
||||
foreach (DataColumn Column in DT.Columns)
|
||||
{
|
||||
if (FldsInfo.Length > 0)
|
||||
{
|
||||
FldsInfo.Append(",");
|
||||
Flds.Append(",");
|
||||
}
|
||||
|
||||
FldsInfo.Append("[" + Column.ColumnName.Replace("'", "''") + "] CHAR(255)");
|
||||
Flds.Append(Column.ColumnName.Replace("'", "''"));
|
||||
}
|
||||
|
||||
// Table Create
|
||||
Cmd = new OleDbCommand("CREATE TABLE " + TableName + "(" + FldsInfo.ToString() + ")", OleDBConn);
|
||||
Cmd.ExecuteNonQuery();
|
||||
|
||||
// Insert Data
|
||||
foreach (DataRow DR in DT.Rows)
|
||||
{
|
||||
StringBuilder Values = new StringBuilder();
|
||||
foreach (DataColumn Column in DT.Columns)
|
||||
{
|
||||
if (Values.Length > 0) Values.Append(",");
|
||||
Values.Append("'" + DR[Column.ColumnName].ToString().Replace("'", "''") + "'");
|
||||
}
|
||||
|
||||
Cmd = new OleDbCommand(
|
||||
"INSERT INTO [" + TableName + "$]" +
|
||||
"(" + Flds.ToString() + ") " +
|
||||
"VALUES (" + Values.ToString() + ")",
|
||||
OleDBConn);
|
||||
Cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
result = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (OleDBConn != null) OleDBConn.Close();
|
||||
try
|
||||
{
|
||||
if (File.Exists(TempFile))
|
||||
{
|
||||
File.Move(TempFile, FileName);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Excel 파일을 DataSet 으로 변환하여 반환한다.
|
||||
/// </summary>
|
||||
/// <param name="ExcelFile">
|
||||
/// 읽어올 Excel File 명(전체경로)입니다.
|
||||
/// </param>
|
||||
public static DataSet OpenExcelDB(string ExcelFile)
|
||||
{
|
||||
return OpenExcel(ExcelFile, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DataSet 을 Excel 파일로 저장한다. 동일 파일명이 있으면 Overwrite 됩니다.
|
||||
/// </summary>
|
||||
/// <param name="ExcelFile">
|
||||
/// 저장할 Excel File 명(전체경로)입니다.
|
||||
/// </param>
|
||||
/// <param name="DS">
|
||||
/// 저장할 대상 DataSet 입니다.
|
||||
/// </param>
|
||||
public static bool SaveExcelDB(string ExcelFile, DataSet DS)
|
||||
{
|
||||
return SaveExcel(ExcelFile, DS, true, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
564
LFP_Manager_PRM/Utils/csLog.cs
Normal file
564
LFP_Manager_PRM/Utils/csLog.cs
Normal file
@@ -0,0 +1,564 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
|
||||
using LFP_Manager.DataStructure;
|
||||
|
||||
namespace LFP_Manager.Utils
|
||||
{
|
||||
class csLog
|
||||
{
|
||||
private static string SYSTEMLOG_FILE_DIR_M = "\\log\\systemlog";
|
||||
private static string SYSTEMLOG_FILE_DIR = "\\log\\systemlog";
|
||||
|
||||
public static string GetLogFolder(string AppPath)
|
||||
{
|
||||
string path = System.IO.Path.GetDirectoryName(AppPath);
|
||||
|
||||
if (Directory.Exists(path + SYSTEMLOG_FILE_DIR_M) == false)
|
||||
Directory.CreateDirectory(path + SYSTEMLOG_FILE_DIR_M);
|
||||
|
||||
return path + SYSTEMLOG_FILE_DIR_M;
|
||||
}
|
||||
|
||||
public static void SystemErrorLog(CommConfig sConfig, string sEvent, DateTime aTime, string AppPath)
|
||||
{
|
||||
SYSTEMLOG_FILE_DIR = string.Format("{0}\\SystemErr\\{1}", "\\log", string.Format("{0:yyyyMM}", aTime));
|
||||
string path = Path.GetDirectoryName(AppPath);
|
||||
string FileName = string.Format(path + SYSTEMLOG_FILE_DIR + "\\{0}_SYS_ERROR_LOG.txt", string.Format("{0:yyMMdd}", aTime));
|
||||
byte[] logData;
|
||||
|
||||
if (Directory.Exists(path + SYSTEMLOG_FILE_DIR) == false)
|
||||
{
|
||||
Directory.CreateDirectory(path + SYSTEMLOG_FILE_DIR);
|
||||
}
|
||||
|
||||
FileStream logFile;
|
||||
if (File.Exists(FileName) == false)
|
||||
{
|
||||
logFile = new FileStream(FileName, FileMode.CreateNew, FileAccess.ReadWrite);
|
||||
logFile.Close();
|
||||
}
|
||||
|
||||
logFile = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
|
||||
|
||||
if (logFile != null)
|
||||
{
|
||||
logFile.Seek(0, SeekOrigin.End);
|
||||
logData = WriteEventData(aTime, sEvent);
|
||||
logFile.Write(logData, 0, logData.Length);
|
||||
logFile.Close();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] WriteEventData(DateTime aLog, String sEvent)
|
||||
{
|
||||
string tt;
|
||||
string sdata;
|
||||
|
||||
tt = aLog.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
sdata = String.Format(
|
||||
"{0} {1}\r\n"
|
||||
, tt // 0 DATETIME
|
||||
, sEvent // 1 Event Log Data
|
||||
);
|
||||
|
||||
Byte[] info =
|
||||
new UTF8Encoding(true).GetBytes(sdata);
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
|
||||
public static void SystemDataLog(int RackID, ref CommConfig sConfig, ref DeviceSystemData sData, DateTime aTime, string AppPath)
|
||||
{
|
||||
SYSTEMLOG_FILE_DIR = String.Format("{0}\\SHELF{1}\\{2}", "\\log\\systemlog", RackID, String.Format("{0:yyyyMM}", aTime));
|
||||
|
||||
FileStream logFile = null;
|
||||
string path = System.IO.Path.GetDirectoryName(AppPath);
|
||||
string FileName = String.Format(path + SYSTEMLOG_FILE_DIR + "\\SHELF{0}_LOG_{1}.csv", RackID, String.Format("{0:yyMMdd}", aTime));
|
||||
byte[] logData;
|
||||
|
||||
if (Directory.Exists(path + SYSTEMLOG_FILE_DIR) == false)
|
||||
Directory.CreateDirectory(path + SYSTEMLOG_FILE_DIR);
|
||||
|
||||
if (File.Exists(FileName) == false)
|
||||
{
|
||||
logFile = new FileStream(FileName, FileMode.CreateNew, FileAccess.ReadWrite);
|
||||
logData = WriteDataHeader(aTime);
|
||||
logFile.Write(logData, 0, logData.Length);
|
||||
logFile.Close();
|
||||
}
|
||||
|
||||
logFile = null;
|
||||
//logFile = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite);
|
||||
logFile = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
|
||||
|
||||
if (logFile != null)
|
||||
{
|
||||
logFile.Seek(0, SeekOrigin.End);
|
||||
logData = WriteData(aTime, sConfig, sData);
|
||||
logFile.Write(logData, 0, logData.Length);
|
||||
logFile.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void SystemTotalDataLog(CommConfig sConfig, DeviceSystemTotalData tData, DateTime aTime, string AppPath, string LogFileName)
|
||||
{
|
||||
SYSTEMLOG_FILE_DIR = String.Format("{0}\\MAIN\\{1}", "\\log\\systemlog", String.Format("{0:yyyyMM}", aTime));
|
||||
|
||||
FileStream logFile = null;
|
||||
string path = System.IO.Path.GetDirectoryName(AppPath);
|
||||
//string FileName = String.Format(path + SYSTEMLOG_FILE_DIR + "\\SHELF{0}_LOG_{1}.csv", RackID, String.Format("{0:yyMMdd}", aTime));
|
||||
string FileName = String.Format(path + SYSTEMLOG_FILE_DIR + "\\MAIN_LOG_{0}.csv", LogFileName);
|
||||
byte[] logData;
|
||||
|
||||
if (Directory.Exists(path + SYSTEMLOG_FILE_DIR) == false)
|
||||
Directory.CreateDirectory(path + SYSTEMLOG_FILE_DIR);
|
||||
|
||||
if (File.Exists(FileName) == false)
|
||||
{
|
||||
logFile = new FileStream(FileName, FileMode.CreateNew, FileAccess.ReadWrite);
|
||||
logData = WriteTotalDataHeader(aTime);
|
||||
logFile.Write(logData, 0, logData.Length);
|
||||
logFile.Close();
|
||||
}
|
||||
|
||||
logFile = null;
|
||||
//logFile = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite);
|
||||
logFile = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
|
||||
|
||||
if (logFile != null)
|
||||
{
|
||||
logFile.Seek(0, SeekOrigin.End);
|
||||
logData = WriteTotalData(aTime, sConfig, tData);
|
||||
logFile.Write(logData, 0, logData.Length);
|
||||
logFile.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void SystemDataLog(int RackID, CommConfig sConfig, DeviceSystemData sData, DateTime aTime, string AppPath, string LogFileName)
|
||||
{
|
||||
SYSTEMLOG_FILE_DIR = String.Format("{0}\\SHELF{1}\\{2}", "\\log\\systemlog", RackID, String.Format("{0:yyyyMM}", aTime));
|
||||
|
||||
FileStream logFile = null;
|
||||
string path = System.IO.Path.GetDirectoryName(AppPath);
|
||||
//string FileName = String.Format(path + SYSTEMLOG_FILE_DIR + "\\SHELF{0}_LOG_{1}.csv", RackID, String.Format("{0:yyMMdd}", aTime));
|
||||
string FileName = String.Format(path + SYSTEMLOG_FILE_DIR + "\\SHELF{0}_LOG_{1}.csv", RackID, LogFileName);
|
||||
byte[] logData;
|
||||
|
||||
if (Directory.Exists(path + SYSTEMLOG_FILE_DIR) == false)
|
||||
Directory.CreateDirectory(path + SYSTEMLOG_FILE_DIR);
|
||||
|
||||
if (File.Exists(FileName) == false)
|
||||
{
|
||||
logFile = new FileStream(FileName, FileMode.CreateNew, FileAccess.ReadWrite);
|
||||
logData = WriteDataHeader(aTime);
|
||||
logFile.Write(logData, 0, logData.Length);
|
||||
logFile.Close();
|
||||
}
|
||||
|
||||
logFile = null;
|
||||
//logFile = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite);
|
||||
logFile = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
|
||||
|
||||
if (logFile != null)
|
||||
{
|
||||
logFile.Seek(0, SeekOrigin.End);
|
||||
logData = WriteData(aTime, sConfig, sData);
|
||||
logFile.Write(logData, 0, logData.Length);
|
||||
logFile.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void MakeCosoleStrLog(CommConfig cConfig, string log)
|
||||
{
|
||||
DateTime aDate = DateTime.Now;
|
||||
string mSN = "";
|
||||
if ((cConfig.mSN == null) || (cConfig.mSN == ""))
|
||||
{
|
||||
mSN = String.Format("00000000");
|
||||
}
|
||||
else
|
||||
{
|
||||
mSN = cConfig.mSN;
|
||||
}
|
||||
|
||||
string filename = string.Format("{0}_CB_TEST_{1:yyMMddHH}.log", mSN, aDate);
|
||||
string filepath =
|
||||
Path.GetDirectoryName(cConfig.AppPath)
|
||||
+ String.Format(@"\test\{0:yyMMdd}\", aDate)
|
||||
+ filename;
|
||||
|
||||
if (Directory.Exists(Path.GetDirectoryName(filepath)) == false)
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(filepath));
|
||||
|
||||
string strlog = log;
|
||||
string flog = String.Format("[{0:yyyy-MM-dd HH:mm:ss}]: {1}\r\n", aDate, strlog);
|
||||
byte[] bLog = Encoding.UTF8.GetBytes(flog);
|
||||
FileStream logFile = null;
|
||||
|
||||
if (File.Exists(filepath) == false)
|
||||
{
|
||||
logFile = new FileStream(filepath, FileMode.CreateNew, FileAccess.ReadWrite);
|
||||
logFile.Seek(0, SeekOrigin.End);
|
||||
logFile.Write(bLog, 0, bLog.Length);
|
||||
logFile.Close();
|
||||
}
|
||||
else
|
||||
{
|
||||
logFile = new FileStream(filepath, FileMode.Open, FileAccess.ReadWrite);
|
||||
logFile.Seek(0, SeekOrigin.End);
|
||||
logFile.Write(bLog, 0, bLog.Length);
|
||||
logFile.Close();
|
||||
}
|
||||
}
|
||||
|
||||
#region SYSTEM DATE LOGGING
|
||||
|
||||
private static byte[] WriteTotalDataHeader(DateTime aDateTime)
|
||||
{
|
||||
string tt;
|
||||
string sdata;
|
||||
|
||||
tt = aDateTime.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
sdata = String.Format(
|
||||
"{0};{1};{2};{3};{4};{5};{6};{7};{8};{9};"
|
||||
, "DATETIME" // 0
|
||||
, "INTERFACE" // 1
|
||||
, "MODEL" // 2
|
||||
, "COMM STATUS" // 3
|
||||
, "STATUS" // 4
|
||||
, "ALARM" // 5
|
||||
, "VOLTAGE" // 6
|
||||
, "CURRENT" // 7
|
||||
, "SOC" // 8
|
||||
, "MAX. TEMP" // 9
|
||||
);
|
||||
sdata += "\r\n";
|
||||
|
||||
Byte[] info =
|
||||
new UTF8Encoding(true).GetBytes(sdata);
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
private static byte[] WriteDataHeader(DateTime aDateTime)
|
||||
{
|
||||
string tt;
|
||||
string sdata;
|
||||
|
||||
tt = aDateTime.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
sdata = String.Format(
|
||||
"{0};{1};{2};{3};{4};{5};{6};{7};{8};"
|
||||
, "DATETIME" // 0
|
||||
, "INTERFACE" // 1
|
||||
, "MODEL" // 2
|
||||
, "COMM STATUS" // 3
|
||||
, "STATUS" // 4
|
||||
, "ALARM" // 5
|
||||
, "VOLTAGE" // 6
|
||||
, "CURRENT" // 7
|
||||
, "SOC" // 8
|
||||
);
|
||||
|
||||
for (int i = 0; i < csConstData.SystemInfo.MAX_MODULE_CELL_SIZE; i++)
|
||||
{
|
||||
sdata += String.Format("{0},", String.Format("Cell_{0}", i + 1));
|
||||
}
|
||||
|
||||
for (int i = 0; i < csConstData.SystemInfo.MAX_MODULE_TEMP_SIZE; i++)
|
||||
{
|
||||
sdata += String.Format("{0},", String.Format("Temp_{0}", i + 1));
|
||||
}
|
||||
|
||||
sdata += String.Format("{0},", String.Format("CPU_Temp"));
|
||||
|
||||
sdata += String.Format(
|
||||
"{0};{1};{2};"
|
||||
, "Warning" // 0
|
||||
, "Fault" // 1
|
||||
, "cellBallanceStatus" // 2
|
||||
);
|
||||
sdata += "\r\n";
|
||||
|
||||
Byte[] info =
|
||||
new UTF8Encoding(true).GetBytes(sdata);
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
private static string GetStatusString(short aStatus)
|
||||
{
|
||||
string result = "";
|
||||
|
||||
if (aStatus == 0)
|
||||
{
|
||||
result = "STANDBY";
|
||||
}
|
||||
else if (aStatus == 1)
|
||||
{
|
||||
result = "CHARGING";
|
||||
}
|
||||
else if (aStatus == 2)
|
||||
{
|
||||
result = "DISCHARGING";
|
||||
}
|
||||
else if (aStatus == 3)
|
||||
{
|
||||
result = "FLOATING";
|
||||
}
|
||||
else
|
||||
{
|
||||
result = "UNKNOWN";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string GetAlarmString(short aAlarm)
|
||||
{
|
||||
string result = "";
|
||||
bool[] rackStatus = csUtils.Int16ToBitArray(aAlarm);
|
||||
|
||||
if (aAlarm == 0) result = "NORMAL";
|
||||
else if (aAlarm == 1) result = "WARNING";
|
||||
else if (aAlarm == 2) result = "FAULT";
|
||||
else if (aAlarm == 3) result = "WARMING UP";
|
||||
else result = "UNKNOWN";
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string GetInterface(int sCommType)
|
||||
{
|
||||
string result = "";
|
||||
|
||||
if (sCommType == 0) result = "SNMP";
|
||||
else if (sCommType == 1) result = "UART";
|
||||
else result = "CAN";
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string GetModelName(CommConfig sConfig)
|
||||
{
|
||||
string result = "";
|
||||
|
||||
if (sConfig.CommType == 0)
|
||||
{
|
||||
// SNMP
|
||||
switch (sConfig.SnmpModelIndex)
|
||||
{
|
||||
case 0: result = "LFPS-4850"; break;
|
||||
case 1: result = "LFPS-4870"; break;
|
||||
case 2: result = "LFPS-48100"; break;
|
||||
case 3: result = "LFPR-48300"; break;
|
||||
case 4: result = "LFPR-48600"; break;
|
||||
case 5: result = "LFPR-48900"; break;
|
||||
case 6: result = "LFPR-481000H"; break;
|
||||
}
|
||||
}
|
||||
else if (sConfig.CommType == 1)
|
||||
{
|
||||
// UART
|
||||
switch (sConfig.UartModelIndex)
|
||||
{
|
||||
case 0: result = "LFPS-48150"; break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// CAN
|
||||
result = "LFPS-48100H";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string GetCommStatus(CommConfig sConfig, DeviceSystemData sData)
|
||||
{
|
||||
string result = "";
|
||||
|
||||
if (sConfig.CommType == 0)
|
||||
{
|
||||
// SNMP
|
||||
if (sData.CommFail == false)
|
||||
{
|
||||
if (sData.ShelfCommFail == false) result = "NORM";
|
||||
else result = "FAIL";
|
||||
}
|
||||
else
|
||||
{
|
||||
result = "OFF-LINE";
|
||||
}
|
||||
}
|
||||
else if (sConfig.CommType == 1)
|
||||
{
|
||||
// UART
|
||||
if (sData.CommFail == false)
|
||||
{
|
||||
result = "NORM";
|
||||
}
|
||||
else
|
||||
{
|
||||
result = "FAIL";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// CAN
|
||||
if (sData.CommFail == false)
|
||||
{
|
||||
result = "NORM";
|
||||
}
|
||||
else
|
||||
{
|
||||
result = "FAIL";
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string GetCommStatus(DeviceSystemTotalData tData)
|
||||
{
|
||||
string result = "";
|
||||
|
||||
if (tData.CommFail)
|
||||
result = "OFF-LINE";
|
||||
else
|
||||
result = "NORM";
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static byte[] WriteTotalData(DateTime aLog, CommConfig sConfig, DeviceSystemTotalData tData)
|
||||
{
|
||||
string tt;
|
||||
string sdata;
|
||||
|
||||
tt = aLog.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
sdata = String.Format(
|
||||
"{0};{1};{2};{3};{4};{5};{6};{7};{8};{9};"
|
||||
, tt // 0 DATETIME
|
||||
, GetInterface(sConfig.CommType) // 1 INTERFACE
|
||||
, GetModelName(sConfig) // 2 MODEL
|
||||
, GetCommStatus(tData) // 3 COMM STATUS
|
||||
, GetStatusString(tData.StatusData.status) // 4 STATUS
|
||||
, GetAlarmString(tData.StatusData.batteryStatus) // 5 ALARM
|
||||
, String.Format("{0:#0.0}", Convert.ToDouble(tData.ValueData.TotalVoltage) / 10) // 6 voltageOfPack
|
||||
, String.Format("{0:#0.0}", Convert.ToDouble(tData.ValueData.TotalCurrent) / 10) // 7 current
|
||||
, String.Format("{0:#0.0}", Convert.ToDouble(tData.ValueData.TotalSOC) / 10) // 8 SOC
|
||||
, String.Format("{0:#0.0}", Convert.ToDouble(tData.ValueData.TotalTemp) / 10) // 9 Max Temperature
|
||||
);
|
||||
sdata += "\r\n";
|
||||
|
||||
Byte[] info =
|
||||
new UTF8Encoding(true).GetBytes(sdata);
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
private static byte[] WriteData(DateTime aLog, CommConfig sConfig, DeviceSystemData sData)
|
||||
{
|
||||
string tt;
|
||||
string sdata;
|
||||
|
||||
tt = aLog.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
sdata = String.Format(
|
||||
"{0};{1};{2};{3};{4};{5};{6};{7};{8};"
|
||||
, tt // 0 DATETIME
|
||||
, GetInterface(sConfig.CommType) // 1 INTERFACE
|
||||
, GetModelName(sConfig) // 2 MODEL
|
||||
, GetCommStatus(sConfig, sData) // 3 COMM STATUS
|
||||
, GetStatusString(sData.StatusData.status) // 4 STATUS
|
||||
, GetAlarmString(sData.StatusData.alarm) // 5 ALARM
|
||||
, String.Format("{0:#0.0}", Convert.ToDouble(sData.ValueData.voltageOfPack) / 10) // 6 voltageOfPack
|
||||
, String.Format("{0:#0.0}", Convert.ToDouble(sData.ValueData.current) / 10) // 7 current
|
||||
, String.Format("{0:#0.0}", Convert.ToDouble(sData.ValueData.rSOC) / 10) // 8 SOC
|
||||
);
|
||||
|
||||
for (int i = 0; i < csConstData.SystemInfo.MAX_MODULE_CELL_SIZE; i++)
|
||||
{
|
||||
sdata += String.Format("{0:#0.000};", Convert.ToDouble(sData.ValueData.CellVoltage[i]) / 1000); // 27 Cell Voltage n
|
||||
}
|
||||
|
||||
for (int i = 0; i < csConstData.SystemInfo.MAX_MODULE_TEMP_SIZE; i++)
|
||||
{
|
||||
sdata += String.Format("{0:#0.0};", Convert.ToDouble(sData.ValueData.CellTemperature[i]) / 10); // 27 Cell Temperature n
|
||||
}
|
||||
|
||||
sdata += String.Format("{0:#0.0};", Convert.ToDouble(sData.ValueData.CpuTemperature) / 10); // 27 Cell Temperature n
|
||||
|
||||
sdata += String.Format(
|
||||
"{0};{1};{2};{3};"
|
||||
, String.Format("0x{0}", sData.StatusData.warning.ToString("X4")) // 0 Warning
|
||||
, String.Format("0x{0}", sData.StatusData.protect.ToString("X4")) // 1 Protection
|
||||
, String.Format("0x{0}", sData.StatusData.cellBallanceStatusLv.ToString("X4")) // 2 cellBallanceStatusLv
|
||||
, String.Format("0x{0}", sData.StatusData.cellBallanceStatusHv.ToString("X4")) // 3 cellBallanceStatusHv
|
||||
);
|
||||
sdata += "\r\n";
|
||||
|
||||
Byte[] info =
|
||||
new UTF8Encoding(true).GetBytes(sdata);
|
||||
|
||||
return info;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region DATA PRINT
|
||||
|
||||
public static string data_print(byte[] data, int len)
|
||||
{
|
||||
byte[] ASC;
|
||||
int i, j;
|
||||
string result = "";
|
||||
|
||||
ASC = new byte[20];
|
||||
|
||||
if (len > 2)
|
||||
{
|
||||
if (ASC != null)
|
||||
{
|
||||
for (i = 0; i < (len / 16 + 1); i++)
|
||||
{
|
||||
result += String.Format("0x{0:X8} ", (int)(i * 16));
|
||||
for (j = 0; j < 16; j++)
|
||||
{
|
||||
if ((i * 16 + j) >= data.Length)
|
||||
{
|
||||
result += " ";
|
||||
ASC[j] = (byte)' ';
|
||||
}
|
||||
else
|
||||
{
|
||||
result += String.Format("{0:X2} ", data[(i * 16) + j]);
|
||||
if (data[i * 16 + j] < ' ')
|
||||
ASC[j] = (byte)'.';
|
||||
else
|
||||
{
|
||||
if ((j == 15) && (data[i * 16 + j] > 128))
|
||||
ASC[j] = (byte)'.';
|
||||
else
|
||||
ASC[j] = data[i * 16 + j];
|
||||
}
|
||||
}
|
||||
}
|
||||
ASC[16] = 0x00;
|
||||
result += "\r\n";
|
||||
//result += String.Format(" {0}\r\n", ASC.ToArray<byte>().ToString());
|
||||
}
|
||||
}
|
||||
result += "\r\n";
|
||||
//result += String.Format("ID: {0:X2}\r\n", data[6]);
|
||||
//result += String.Format("CMD: {0:X2}\r\n", data[7]);
|
||||
//result += String.Format("S-A: {0:X4}({0:d})\r\n", (data[8] << 8) | data[9]);
|
||||
//result += String.Format("S-L: {0:X4}({0:d})\r\n", (data[10] << 8) | data[11]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
209
LFP_Manager_PRM/Utils/csUtils.cs
Normal file
209
LFP_Manager_PRM/Utils/csUtils.cs
Normal file
@@ -0,0 +1,209 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Windows.Forms;
|
||||
|
||||
using LFP_Manager.DataStructure;
|
||||
|
||||
namespace LFP_Manager.Utils
|
||||
{
|
||||
static class csUtils
|
||||
{
|
||||
public static int GetModuleQty(CommConfig aConfig)
|
||||
{
|
||||
int mQty = 1;
|
||||
|
||||
switch (aConfig.CommType)
|
||||
{
|
||||
case csConstData.CommType.COMM_SNMP:
|
||||
switch (aConfig.SnmpModelIndex)
|
||||
{
|
||||
case 6: // LFPR-481000H
|
||||
mQty = aConfig.SnmpMdQty;
|
||||
break;
|
||||
case 5: // LFPR-48900
|
||||
mQty = 3;
|
||||
break;
|
||||
case 4: // LFPR-48600
|
||||
mQty = 2;
|
||||
break;
|
||||
default:
|
||||
mQty = 1;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case csConstData.CommType.COMM_UARTCAN:
|
||||
mQty = 1;
|
||||
break;
|
||||
case csConstData.CommType.COMM_USBCAN:
|
||||
mQty = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
return mQty;
|
||||
}
|
||||
|
||||
public static void TypingOnlyNumber(object sender, KeyPressEventArgs e, bool includePoint, bool includeMinus)
|
||||
{
|
||||
bool isValidInput = false;
|
||||
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
|
||||
{
|
||||
if (includePoint == true) { if (e.KeyChar == '.') isValidInput = true; }
|
||||
if (includeMinus == true) { if (e.KeyChar == '-') isValidInput = true; }
|
||||
|
||||
if (isValidInput == false) e.Handled = true;
|
||||
}
|
||||
|
||||
if (includePoint == true)
|
||||
{
|
||||
if (e.KeyChar == '.' && (string.IsNullOrEmpty((sender as DevExpress.XtraEditors.TextEdit).Text.Trim()) || (sender as DevExpress.XtraEditors.TextEdit).Text.IndexOf('.') > -1)) e.Handled = true;
|
||||
}
|
||||
if (includeMinus == true)
|
||||
{
|
||||
if (e.KeyChar == '-' && (!string.IsNullOrEmpty((sender as DevExpress.XtraEditors.TextEdit).Text.Trim()) || (sender as DevExpress.XtraEditors.TextEdit).Text.IndexOf('-') > -1)) e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool[] Int16ToBitArray(Int16 data)
|
||||
{
|
||||
bool[] result = new bool[16];
|
||||
|
||||
for (int i = 0; i < 16; i++)
|
||||
{
|
||||
result[i] = (((data >> i) & 0x0001) == 0x0001) ? true : false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static byte[] GetCRC(byte[] pby, UInt16 nSize)
|
||||
{
|
||||
byte[] result = new byte[2];
|
||||
UInt16 uIndex, i;
|
||||
UInt16 crc;
|
||||
byte uchCRCHi = 0xff;
|
||||
byte uchCRCLo = 0xff;
|
||||
|
||||
for (i = 0; i < nSize; i++)
|
||||
{
|
||||
uIndex = (UInt16)(uchCRCHi ^ pby[i]);
|
||||
uchCRCHi = (byte)(uchCRCLo ^ csConstData.CRC.AuchCRCHi[uIndex]);
|
||||
uchCRCLo = csConstData.CRC.AuchCRCLo[uIndex];
|
||||
}
|
||||
crc = (UInt16)(((UInt16)uchCRCHi << 8) | uchCRCLo);
|
||||
|
||||
result[1] = (byte)(crc / 256);
|
||||
result[0] = (byte)(crc % 256);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static byte StrByte2toByte(byte a, byte b)
|
||||
{
|
||||
byte result = 0;
|
||||
byte a1 = 0, b1 = 0;
|
||||
|
||||
if ((a >= (byte)'0')&&(a <= (byte)'9'))
|
||||
{
|
||||
a1 = (byte)(a - (byte)'0');
|
||||
}
|
||||
else if ((a >= (byte)'a')&&(a <= (byte)'f'))
|
||||
{
|
||||
a1 = (byte)(a - (byte)'a');
|
||||
}
|
||||
else if ((a >= (byte)'A')&&(a <= (byte)'F'))
|
||||
{
|
||||
a1 = (byte)((a - (byte)'A') + 0x0A);
|
||||
}
|
||||
|
||||
if ((b >= (byte)'0') && (b <= (byte)'9'))
|
||||
{
|
||||
b1 = (byte)(b - (byte)'0');
|
||||
}
|
||||
else if ((b >= (byte)'a') && (b <= (byte)'f'))
|
||||
{
|
||||
b1 = (byte)(b - (byte)'a');
|
||||
}
|
||||
else if ((b >= (byte)'A') && (b <= (byte)'F'))
|
||||
{
|
||||
b1 = (byte)((b - (byte)'A') + 0x0A);
|
||||
}
|
||||
|
||||
result = (byte)((b1 << 4) | a1);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static byte[] StrToByteArray(byte[] rData, int offset, int rlen)
|
||||
{
|
||||
int len = (rlen - 2) / 2;
|
||||
byte[] result = new byte[len];
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
result[i] = StrByte2toByte(rData[(i * 2) + offset + 2], rData[(i * 2) + offset + 1]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static byte[] StringToByte(string str)
|
||||
{
|
||||
byte[] StrByte = Encoding.UTF8.GetBytes(str); return StrByte;
|
||||
}
|
||||
|
||||
public static long UnixTimeNow()
|
||||
{
|
||||
var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
|
||||
return (long)timeSpan.TotalSeconds;
|
||||
}
|
||||
|
||||
#region OPERATING WARNING FUCTION
|
||||
|
||||
public static bool BitCheck(short rData, int pos)
|
||||
{
|
||||
if (((rData >> pos) & 0x0001) == 0x0001)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
public static UInt32 CalcKKTimeStamp(DateTime tDate)
|
||||
{
|
||||
//Time of test and calibration. Local time in seconds since 2000.
|
||||
//Ex:
|
||||
//Epoch time offset (1 January 2000 00:00:00) = 946684800
|
||||
//Current epoch time (1 October 2019 12:00:00) = 1569931200
|
||||
//Timestamp = 1569931200 - 946684800 = 623246400
|
||||
//(Used 'https://www.epochconverter.com/' for conversion)
|
||||
DateTime baseDate = new DateTime(2000, 1, 1, 0, 0, 0);
|
||||
|
||||
int bDate = ConvertToUnixTimestamp(baseDate);
|
||||
int nDate = ConvertToUnixTimestamp(tDate);
|
||||
|
||||
return (UInt32)(nDate - bDate);
|
||||
}
|
||||
|
||||
public static DateTime ConvertTimeStampToDateTime(UInt32 tStamp)
|
||||
{
|
||||
DateTime result = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
result = result.AddSeconds(tStamp);
|
||||
|
||||
// DateTimeOffset.Now.ToUnixTimeSeconds() // (.NET Framework 4.6 +/.NET Core),
|
||||
// older versions:
|
||||
//var epoch = (DateTime.UtcNow - new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int ConvertToUnixTimestamp(DateTime date)
|
||||
{
|
||||
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0);
|
||||
TimeSpan diff = date - origin;
|
||||
return (int)Math.Floor(diff.TotalSeconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
166
LFP_Manager_PRM/Utils/globalKeyboardHook.cs
Normal file
166
LFP_Manager_PRM/Utils/globalKeyboardHook.cs
Normal file
@@ -0,0 +1,166 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace LFP_Manager.Utils
|
||||
{
|
||||
/// <summary>
|
||||
/// A class that manages a global low level keyboard hook
|
||||
/// </summary>
|
||||
class globalKeyboardHook
|
||||
{
|
||||
#region Constant, Structure and Delegate Definitions
|
||||
/// <summary>
|
||||
/// defines the callback type for the hook
|
||||
/// </summary>
|
||||
public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
|
||||
|
||||
public struct keyboardHookStruct
|
||||
{
|
||||
public int vkCode;
|
||||
public int scanCode;
|
||||
public int flags;
|
||||
public int time;
|
||||
public int dwExtraInfo;
|
||||
}
|
||||
|
||||
const int WH_KEYBOARD_LL = 13;
|
||||
const int WM_KEYDOWN = 0x100;
|
||||
const int WM_KEYUP = 0x101;
|
||||
const int WM_SYSKEYDOWN = 0x104;
|
||||
const int WM_SYSKEYUP = 0x105;
|
||||
#endregion
|
||||
|
||||
#region Instance Variables
|
||||
/// <summary>
|
||||
/// The collections of keys to watch for
|
||||
/// </summary>
|
||||
public List<Keys> HookedKeys = new List<Keys>();
|
||||
/// <summary>
|
||||
/// Handle to the hook, need this to unhook and call the next hook
|
||||
/// </summary>
|
||||
IntPtr hhook = IntPtr.Zero;
|
||||
#endregion
|
||||
|
||||
#region Events
|
||||
/// <summary>
|
||||
/// Occurs when one of the hooked keys is pressed
|
||||
/// </summary>
|
||||
public event KeyEventHandler KeyDown;
|
||||
/// <summary>
|
||||
/// Occurs when one of the hooked keys is released
|
||||
/// </summary>
|
||||
public event KeyEventHandler KeyUp;
|
||||
#endregion
|
||||
|
||||
#region Constructors and Destructors
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="globalKeyboardHook"/> class and installs the keyboard hook.
|
||||
/// </summary>
|
||||
public globalKeyboardHook()
|
||||
{
|
||||
hook();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases unmanaged resources and performs other cleanup operations before the
|
||||
/// <see cref="globalKeyboardHook"/> is reclaimed by garbage collection and uninstalls the keyboard hook.
|
||||
/// </summary>
|
||||
~globalKeyboardHook()
|
||||
{
|
||||
unhook();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
/// <summary>
|
||||
/// Installs the global hook
|
||||
/// </summary>
|
||||
public void hook()
|
||||
{
|
||||
IntPtr hInstance = LoadLibrary("User32");
|
||||
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Uninstalls the global hook
|
||||
/// </summary>
|
||||
public void unhook()
|
||||
{
|
||||
UnhookWindowsHookEx(hhook);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The callback for the keyboard hook
|
||||
/// </summary>
|
||||
/// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param>
|
||||
/// <param name="wParam">The event type</param>
|
||||
/// <param name="lParam">The keyhook event information</param>
|
||||
/// <returns></returns>
|
||||
public int hookProc(int code, int wParam, ref keyboardHookStruct lParam)
|
||||
{
|
||||
if (code >= 0)
|
||||
{
|
||||
Keys key = (Keys)lParam.vkCode;
|
||||
if (HookedKeys.Contains(key))
|
||||
{
|
||||
KeyEventArgs kea = new KeyEventArgs(key);
|
||||
if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null))
|
||||
{
|
||||
KeyDown(this, kea);
|
||||
}
|
||||
else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null))
|
||||
{
|
||||
KeyUp(this, kea);
|
||||
}
|
||||
if (kea.Handled)
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return CallNextHookEx(hhook, code, wParam, ref lParam);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region DLL imports
|
||||
/// <summary>
|
||||
/// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
|
||||
/// </summary>
|
||||
/// <param name="idHook">The id of the event you want to hook</param>
|
||||
/// <param name="callback">The callback.</param>
|
||||
/// <param name="hInstance">The handle you want to attach the event to, can be null</param>
|
||||
/// <param name="threadId">The thread you want to attach the event to, can be null</param>
|
||||
/// <returns>a handle to the desired hook</returns>
|
||||
[DllImport("user32.dll")]
|
||||
static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
|
||||
|
||||
/// <summary>
|
||||
/// Unhooks the windows hook.
|
||||
/// </summary>
|
||||
/// <param name="hInstance">The hook handle that was returned from SetWindowsHookEx</param>
|
||||
/// <returns>True if successful, false otherwise</returns>
|
||||
[DllImport("user32.dll")]
|
||||
static extern bool UnhookWindowsHookEx(IntPtr hInstance);
|
||||
|
||||
/// <summary>
|
||||
/// Calls the next hook.
|
||||
/// </summary>
|
||||
/// <param name="idHook">The hook id</param>
|
||||
/// <param name="nCode">The hook code</param>
|
||||
/// <param name="wParam">The wparam.</param>
|
||||
/// <param name="lParam">The lparam.</param>
|
||||
/// <returns></returns>
|
||||
[DllImport("user32.dll")]
|
||||
static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
|
||||
|
||||
/// <summary>
|
||||
/// Loads the library.
|
||||
/// </summary>
|
||||
/// <param name="lpFileName">Name of the library</param>
|
||||
/// <returns>A handle to the library</returns>
|
||||
[DllImport("kernel32.dll")]
|
||||
static extern IntPtr LoadLibrary(string lpFileName);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user