版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

322 lines
13 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace AssistClient.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. /// <summary>
  46. /// 处理回调时需锁定
  47. /// </summary>
  48. public bool isLock { get; set; }
  49. public bool start()
  50. {
  51. try
  52. {
  53. if (hKeyboardHook == 0)
  54. {
  55. hookproc = new HookProc(KeyboardHookProc);
  56. //GetModuleHandle 函数 替代 Marshal.GetHINSTANCE
  57. //防止在 framework4.0中 注册钩子不成功
  58. IntPtr modulePtr = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
  59. //WH_KEYBOARD_LL=13
  60. //全局钩子 WH_KEYBOARD_LL
  61. // hKeyboardHook = SetWindowsHookEx(13, hookproc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
  62. hKeyboardHook = SetWindowsHookEx(13, hookproc, modulePtr, 0);
  63. }
  64. return (hKeyboardHook != 0);
  65. }
  66. catch (Exception ex)
  67. {
  68. WarningEvent?.Invoke(WarningEnum.Normal,ex.Message);
  69. return false;
  70. }
  71. }
  72. public bool stop()
  73. {
  74. try
  75. {
  76. if (hKeyboardHook != 0)
  77. {
  78. bool retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
  79. hookproc = null;
  80. hKeyboardHook = 0;
  81. return retKeyboard;
  82. }
  83. return true;
  84. }
  85. catch
  86. {
  87. return false;
  88. }
  89. }
  90. private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
  91. {
  92. try
  93. {
  94. EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg));
  95. codes.Add(msg);
  96. if (msg.message == 13 && msg.paramH > 0 && !string.IsNullOrWhiteSpace(codes.Result))
  97. {
  98. ScanerEvent?.Invoke(codes.Result);
  99. }
  100. return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
  101. }
  102. catch (Exception ex)
  103. {
  104. return 0;
  105. }
  106. }
  107. public void Dispose()
  108. {
  109. stop();
  110. }
  111. public class ScanerCodes
  112. {
  113. private int ts = 100; // 指定输入间隔为300毫秒以内时为连续输入
  114. private List<List<EventMsg>> _keys = new List<List<EventMsg>>();
  115. private List<int> _keydown = new List<int>(); // 保存组合键状态
  116. private List<string> _result = new List<string>(); // 返回结果集
  117. private DateTime _last = DateTime.Now;
  118. private byte[] _state = new byte[256];
  119. private string _key = string.Empty;
  120. private string _cur = string.Empty;
  121. public EventMsg Event
  122. {
  123. get
  124. {
  125. if (_keys.Count == 0)
  126. {
  127. return new EventMsg();
  128. }
  129. else
  130. {
  131. return _keys[_keys.Count - 1][_keys[_keys.Count - 1].Count - 1];
  132. }
  133. }
  134. }
  135. public List<int> KeyDowns
  136. {
  137. get
  138. {
  139. return _keydown;
  140. }
  141. }
  142. public DateTime LastInput
  143. {
  144. get
  145. {
  146. return _last;
  147. }
  148. }
  149. public byte[] KeyboardState
  150. {
  151. get
  152. {
  153. return _state;
  154. }
  155. }
  156. public int KeyDownCount
  157. {
  158. get
  159. {
  160. return _keydown.Count;
  161. }
  162. }
  163. public string Result
  164. {
  165. get
  166. {
  167. if (_result.Count > 0)
  168. {
  169. return _result[_result.Count - 1].Trim();
  170. }
  171. else
  172. {
  173. return null;
  174. }
  175. }
  176. }
  177. public string CurrentKey
  178. {
  179. get
  180. {
  181. return _key;
  182. }
  183. }
  184. public string CurrentChar
  185. {
  186. get
  187. {
  188. return _cur;
  189. }
  190. }
  191. public bool isShift
  192. {
  193. get
  194. {
  195. return _keydown.Contains(160);
  196. }
  197. }
  198. public void Add(EventMsg msg)
  199. {
  200. #region 记录按键信息
  201. // 首次按下按键
  202. if (_keys.Count == 0)
  203. {
  204. _keys.Add(new List<EventMsg>());
  205. _keys[0].Add(msg);
  206. _result.Add(string.Empty);
  207. }
  208. // 未释放其他按键时按下按键
  209. else if (_keydown.Count > 0)
  210. {
  211. _keys[_keys.Count - 1].Add(msg);
  212. }
  213. // 单位时间内按下按键
  214. else if (((TimeSpan)(DateTime.Now - _last)).TotalMilliseconds < ts)
  215. {
  216. _keys[_keys.Count - 1].Add(msg);
  217. }
  218. // 从新记录输入内容
  219. else
  220. {
  221. _keys.Add(new List<EventMsg>());
  222. _keys[_keys.Count - 1].Add(msg);
  223. _result.Add(string.Empty);
  224. }
  225. #endregion
  226. _last = DateTime.Now;
  227. #region 获取键盘状态
  228. // 记录正在按下的按键
  229. if (msg.paramH == 0 && !_keydown.Contains(msg.message))
  230. {
  231. _keydown.Add(msg.message);
  232. }
  233. // 清除已松开的按键
  234. if (msg.paramH > 0 && _keydown.Contains(msg.message))
  235. {
  236. _keydown.Remove(msg.message);
  237. }
  238. #endregion
  239. #region 计算按键信息
  240. int v = msg.message & 0xff;
  241. int c = msg.paramL & 0xff;
  242. StringBuilder strKeyName = new StringBuilder(500);
  243. if (GetKeyNameText(c * 65536, strKeyName, 255) > 0)
  244. {
  245. _key = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
  246. GetKeyboardState(_state);
  247. if (_key.Length == 1 && msg.paramH == 0)// && msg.paramH == 0
  248. {
  249. // 根据键盘状态和shift缓存判断输出字符
  250. _cur = ShiftChar(_key, isShift, _state).ToString();
  251. _result[_result.Count - 1] += _cur;
  252. }
  253. //判断是+ 强制添加+
  254. else if (_key.Length == 5 && msg.paramH == 0 && msg.paramL == 78 && msg.message == 107)
  255. {
  256. // 根据键盘状态和shift缓存判断输出字符
  257. _cur = Convert.ToChar('+').ToString();
  258. _result[_result.Count - 1] += _cur;
  259. }
  260. // 备选          
  261. else
  262. {
  263. _cur = string.Empty;
  264. }
  265. }
  266. #endregion
  267. }
  268. private char ShiftChar(string k, bool isShiftDown, byte[] state)
  269. {
  270. bool capslock = state[0x14] == 1;
  271. bool numlock = state[0x90] == 1;
  272. bool scrolllock = state[0x91] == 1;
  273. bool shiftdown = state[0xa0] == 1;
  274. char chr = (capslock ? k.ToUpper() : k.ToLower()).ToCharArray()[0];
  275. if (isShiftDown)
  276. {
  277. if (chr >= 'a' && chr <= 'z')
  278. {
  279. chr = (char)((int)chr - 32);
  280. }
  281. else if (chr >= 'A' && chr <= 'Z')
  282. {
  283. if (chr == 'Z')
  284. {
  285. string s = "";
  286. }
  287. chr = (char)((int)chr + 32);
  288. }
  289. else
  290. {
  291. string s = "`1234567890-=[];',./";
  292. string u = "~!@#$%^&*()_+{}:\"<>?";
  293. if (s.IndexOf(chr) >= 0)
  294. {
  295. return (u.ToCharArray())[s.IndexOf(chr)];
  296. }
  297. }
  298. }
  299. return chr;
  300. }
  301. }
  302. public struct EventMsg
  303. {
  304. public int message;
  305. public int paramL;
  306. public int paramH;
  307. public int Time;
  308. public int hwnd;
  309. }
  310. }
  311. }