版博士V2.0程序
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

318 líneas
12 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace ProductionControl.Device
  7. {
  8. public class CodeScannerDev:IDisposable
  9. {
  10. #region WIN32API
  11. //private const int WM_KEYDOWN = 0x100;//KEYDOWN       
  12. //private const int WM_KEYUP = 0x101;//KEYUP       
  13. //private const int WM_SYSKEYDOWN = 0x104;//SYSKEYDOWN       
  14. //private const int WM_SYSKEYUP = 0x105;//SYSKEYUP
  15. //private static int HookProc(int nCode, Int32 wParam, IntPtr lParam);
  16. private int hKeyboardHook = 0;//声明键盘钩子处理的初始值
  17. private ScanerCodes codes = new ScanerCodes();//13为键盘钩子
  18. //定义成静态,这样不会抛出回收异常
  19. private static HookProc hookproc;
  20. delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
  21. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]     //设置钩子
  22. private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
  23. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]     //卸载钩子
  24. private static extern bool UnhookWindowsHookEx(int idHook);
  25. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] //继续下个钩子
  26. private static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
  27. [DllImport("user32", EntryPoint = "GetKeyNameText")]
  28. private static extern int GetKeyNameText(int IParam, StringBuilder lpBuffer, int nSize);
  29. [DllImport("user32", EntryPoint = "GetKeyboardState")]     //获取按键的状态
  30. private static extern int GetKeyboardState(byte[] pbKeyState);
  31. [DllImport("user32", EntryPoint = "ToAscii")]     //ToAscii职能的转换指定的虚拟键码和键盘状态的相应字符或字符
  32. private static extern bool ToAscii(int VirtualKey, int ScanCode, byte[] lpKeySate, ref uint lpChar, int uFlags);
  33. //int VirtualKey //[in] 指定虚拟关键代码进行翻译。      
  34. //int uScanCode, // [in] 指定的硬件扫描码的关键须翻译成英文。高阶位的这个值设定的关键,如果是(不压)      
  35. //byte[] lpbKeyState, // [in] 指针,以256字节数组,包含当前键盘的状态。每个元素(字节)的数组包含状态的一个关键。如果高阶位的字节是一套,关键是下跌(按下)。在低比特,如/果设置表明,关键是对切换。在此功能,只有肘位的CAPS LOCK键是相关的。在切换状态的NUM个锁和滚动锁定键被忽略。      //byte[] lpwTransKey, // [out] 指针的缓冲区收到翻译字符或字符。      //uint fuState); // [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
  36. [DllImport("kernel32.dll")]     //使用WINDOWS API函数代替获取当前实例的函数,防止钩子失效
  37. private static extern IntPtr GetModuleHandle(string name);
  38. #endregion
  39. public Action<WarningEnum, string> WarningEvent;
  40. //public Action<ScanerCodes> ScanerEvent;
  41. public Action<string> ScanerEvent;
  42. public CodeScannerDev()
  43. {
  44. }
  45. public bool start()
  46. {
  47. try
  48. {
  49. if (hKeyboardHook == 0)
  50. {
  51. hookproc = new HookProc(KeyboardHookProc);
  52. //GetModuleHandle 函数 替代 Marshal.GetHINSTANCE
  53. //防止在 framework4.0中 注册钩子不成功
  54. IntPtr modulePtr = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
  55. //WH_KEYBOARD_LL=13
  56. //全局钩子 WH_KEYBOARD_LL
  57. // hKeyboardHook = SetWindowsHookEx(13, hookproc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
  58. hKeyboardHook = SetWindowsHookEx(13, hookproc, modulePtr, 0);
  59. }
  60. return (hKeyboardHook != 0);
  61. }
  62. catch (Exception ex)
  63. {
  64. WarningEvent?.Invoke(WarningEnum.Normal,ex.Message);
  65. return false;
  66. }
  67. }
  68. public bool stop()
  69. {
  70. try
  71. {
  72. if (hKeyboardHook != 0)
  73. {
  74. bool retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
  75. hookproc = null;
  76. hKeyboardHook = 0;
  77. return retKeyboard;
  78. }
  79. return true;
  80. }
  81. catch
  82. {
  83. return false;
  84. }
  85. }
  86. private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
  87. {
  88. try
  89. {
  90. EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg));
  91. codes.Add(msg);
  92. if (msg.message == 13 && msg.paramH > 0 && !string.IsNullOrWhiteSpace(codes.Result))
  93. {
  94. ScanerEvent?.Invoke(codes.Result);
  95. }
  96. return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
  97. }
  98. catch (Exception ex)
  99. {
  100. return 0;
  101. }
  102. }
  103. public void Dispose()
  104. {
  105. stop();
  106. }
  107. public class ScanerCodes
  108. {
  109. private int ts = 100; // 指定输入间隔为300毫秒以内时为连续输入
  110. private List<List<EventMsg>> _keys = new List<List<EventMsg>>();
  111. private List<int> _keydown = new List<int>(); // 保存组合键状态
  112. private List<string> _result = new List<string>(); // 返回结果集
  113. private DateTime _last = DateTime.Now;
  114. private byte[] _state = new byte[256];
  115. private string _key = string.Empty;
  116. private string _cur = string.Empty;
  117. public EventMsg Event
  118. {
  119. get
  120. {
  121. if (_keys.Count == 0)
  122. {
  123. return new EventMsg();
  124. }
  125. else
  126. {
  127. return _keys[_keys.Count - 1][_keys[_keys.Count - 1].Count - 1];
  128. }
  129. }
  130. }
  131. public List<int> KeyDowns
  132. {
  133. get
  134. {
  135. return _keydown;
  136. }
  137. }
  138. public DateTime LastInput
  139. {
  140. get
  141. {
  142. return _last;
  143. }
  144. }
  145. public byte[] KeyboardState
  146. {
  147. get
  148. {
  149. return _state;
  150. }
  151. }
  152. public int KeyDownCount
  153. {
  154. get
  155. {
  156. return _keydown.Count;
  157. }
  158. }
  159. public string Result
  160. {
  161. get
  162. {
  163. if (_result.Count > 0)
  164. {
  165. return _result[_result.Count - 1].Trim();
  166. }
  167. else
  168. {
  169. return null;
  170. }
  171. }
  172. }
  173. public string CurrentKey
  174. {
  175. get
  176. {
  177. return _key;
  178. }
  179. }
  180. public string CurrentChar
  181. {
  182. get
  183. {
  184. return _cur;
  185. }
  186. }
  187. public bool isShift
  188. {
  189. get
  190. {
  191. return _keydown.Contains(160);
  192. }
  193. }
  194. public void Add(EventMsg msg)
  195. {
  196. #region 记录按键信息
  197. // 首次按下按键
  198. if (_keys.Count == 0)
  199. {
  200. _keys.Add(new List<EventMsg>());
  201. _keys[0].Add(msg);
  202. _result.Add(string.Empty);
  203. }
  204. // 未释放其他按键时按下按键
  205. else if (_keydown.Count > 0)
  206. {
  207. _keys[_keys.Count - 1].Add(msg);
  208. }
  209. // 单位时间内按下按键
  210. else if (((TimeSpan)(DateTime.Now - _last)).TotalMilliseconds < ts)
  211. {
  212. _keys[_keys.Count - 1].Add(msg);
  213. }
  214. // 从新记录输入内容
  215. else
  216. {
  217. _keys.Add(new List<EventMsg>());
  218. _keys[_keys.Count - 1].Add(msg);
  219. _result.Add(string.Empty);
  220. }
  221. #endregion
  222. _last = DateTime.Now;
  223. #region 获取键盘状态
  224. // 记录正在按下的按键
  225. if (msg.paramH == 0 && !_keydown.Contains(msg.message))
  226. {
  227. _keydown.Add(msg.message);
  228. }
  229. // 清除已松开的按键
  230. if (msg.paramH > 0 && _keydown.Contains(msg.message))
  231. {
  232. _keydown.Remove(msg.message);
  233. }
  234. #endregion
  235. #region 计算按键信息
  236. int v = msg.message & 0xff;
  237. int c = msg.paramL & 0xff;
  238. StringBuilder strKeyName = new StringBuilder(500);
  239. if (GetKeyNameText(c * 65536, strKeyName, 255) > 0)
  240. {
  241. _key = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
  242. GetKeyboardState(_state);
  243. if (_key.Length == 1 && msg.paramH == 0)// && msg.paramH == 0
  244. {
  245. // 根据键盘状态和shift缓存判断输出字符
  246. _cur = ShiftChar(_key, isShift, _state).ToString();
  247. _result[_result.Count - 1] += _cur;
  248. }
  249. //判断是+ 强制添加+
  250. else if (_key.Length == 5 && msg.paramH == 0 && msg.paramL == 78 && msg.message == 107)
  251. {
  252. // 根据键盘状态和shift缓存判断输出字符
  253. _cur = Convert.ToChar('+').ToString();
  254. _result[_result.Count - 1] += _cur;
  255. }
  256. // 备选          
  257. else
  258. {
  259. _cur = string.Empty;
  260. }
  261. }
  262. #endregion
  263. }
  264. private char ShiftChar(string k, bool isShiftDown, byte[] state)
  265. {
  266. bool capslock = state[0x14] == 1;
  267. bool numlock = state[0x90] == 1;
  268. bool scrolllock = state[0x91] == 1;
  269. bool shiftdown = state[0xa0] == 1;
  270. char chr = (capslock ? k.ToUpper() : k.ToLower()).ToCharArray()[0];
  271. if (isShiftDown)
  272. {
  273. if (chr >= 'a' && chr <= 'z')
  274. {
  275. chr = (char)((int)chr - 32);
  276. }
  277. else if (chr >= 'A' && chr <= 'Z')
  278. {
  279. if (chr == 'Z')
  280. {
  281. string s = "";
  282. }
  283. chr = (char)((int)chr + 32);
  284. }
  285. else
  286. {
  287. string s = "`1234567890-=[];',./";
  288. string u = "~!@#$%^&*()_+{}:\"<>?";
  289. if (s.IndexOf(chr) >= 0)
  290. {
  291. return (u.ToCharArray())[s.IndexOf(chr)];
  292. }
  293. }
  294. }
  295. return chr;
  296. }
  297. }
  298. public struct EventMsg
  299. {
  300. public int message;
  301. public int paramL;
  302. public int paramH;
  303. public int Time;
  304. public int hwnd;
  305. }
  306. }
  307. }