UsbScanerHook.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace felixyin
  9. {
  10. class UsbScanerHook
  11. {
  12. public delegate void ScanerDelegate(ScanerCodes codes);
  13. public event ScanerDelegate ScanerEvent;
  14. delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
  15. private int hKeyboardHook = 0;
  16. private ScanerCodes codes = new ScanerCodes();
  17. private HookProc hookproc;
  18. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  19. private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
  20. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  21. private static extern bool UnhookWindowsHookEx(int idHook);
  22. [DllImport("user32", EntryPoint = "GetKeyNameText")]
  23. private static extern int GetKeyNameText(int IParam, StringBuilder lpBuffer, int nSize);
  24. [DllImport("user32", EntryPoint = "GetKeyboardState")]
  25. private static extern int GetKeyboardState(byte[] pbKeyState);
  26. [DllImport("user32", EntryPoint = "ToAscii")]
  27. private static extern bool ToAscii(int VirtualKey, int ScanCode, byte[] lpKeySate, ref uint lpChar, int uFlags);
  28. [DllImport("kernel32.dll")]
  29. public static extern IntPtr GetModuleHandle(string name);
  30. public UsbScanerHook()
  31. {
  32. }
  33. public bool Start()
  34. {
  35. if (hKeyboardHook == 0)
  36. {
  37. hookproc = new HookProc(KeyboardHookProc);
  38. //GetModuleHandle 函数 替代 Marshal.GetHINSTANCE
  39. //防止在 framework4.0中 注册钩子不成功
  40. IntPtr modulePtr = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
  41. //WH_KEYBOARD_LL=13
  42. //全局钩子 WH_KEYBOARD_LL
  43. // hKeyboardHook = SetWindowsHookEx(13, hookproc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
  44. hKeyboardHook = SetWindowsHookEx(13, hookproc, modulePtr, 0);
  45. }
  46. return (hKeyboardHook != 0);
  47. }
  48. public bool Stop()
  49. {
  50. if (hKeyboardHook != 0)
  51. {
  52. return UnhookWindowsHookEx(hKeyboardHook);
  53. }
  54. return true;
  55. }
  56. private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
  57. {
  58. EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg));
  59. codes.Add(msg);
  60. if (ScanerEvent != null && msg.message == 13 && msg.paramH > 0 && !string.IsNullOrEmpty(codes.Result))
  61. {
  62. ScanerEvent(codes);
  63. }
  64. return 0;
  65. }
  66. public class ScanerCodes
  67. {
  68. private int ts = 50; // 指定输入间隔为300毫秒以内时为连续输入
  69. private List<List<EventMsg>> _keys = new List<List<EventMsg>>();
  70. private List<int> _keydown = new List<int>(); // 保存组合键状态
  71. private List<string> _result = new List<string>(); // 返回结果集
  72. private DateTime _last = DateTime.Now;
  73. private byte[] _state = new byte[256];
  74. private string _key = string.Empty;
  75. private string _cur = string.Empty;
  76. public EventMsg Event
  77. {
  78. get
  79. {
  80. if (_keys.Count == 0)
  81. {
  82. return new EventMsg();
  83. }
  84. else
  85. {
  86. return _keys[_keys.Count - 1][_keys[_keys.Count - 1].Count - 1];
  87. }
  88. }
  89. }
  90. public List<int> KeyDowns
  91. {
  92. get
  93. {
  94. return _keydown;
  95. }
  96. }
  97. public DateTime LastInput
  98. {
  99. get
  100. {
  101. return _last;
  102. }
  103. }
  104. public byte[] KeyboardState
  105. {
  106. get
  107. {
  108. return _state;
  109. }
  110. }
  111. public int KeyDownCount
  112. {
  113. get
  114. {
  115. return _keydown.Count;
  116. }
  117. }
  118. public string Result
  119. {
  120. get
  121. {
  122. if (_result.Count > 0)
  123. {
  124. return _result[_result.Count - 1].Trim();
  125. }
  126. else
  127. {
  128. return null;
  129. }
  130. }
  131. }
  132. public string CurrentKey
  133. {
  134. get
  135. {
  136. return _key;
  137. }
  138. }
  139. public string CurrentChar
  140. {
  141. get
  142. {
  143. return _cur;
  144. }
  145. }
  146. public bool isShift
  147. {
  148. get
  149. {
  150. return _keydown.Contains(160);
  151. }
  152. }
  153. public void Add(EventMsg msg)
  154. {
  155. #region 记录按键信息
  156. // 首次按下按键
  157. if (_keys.Count == 0)
  158. {
  159. _keys.Add(new List<EventMsg>());
  160. _keys[0].Add(msg);
  161. _result.Add(string.Empty);
  162. }
  163. // 未释放其他按键时按下按键
  164. else if (_keydown.Count > 0)
  165. {
  166. _keys[_keys.Count - 1].Add(msg);
  167. }
  168. // 单位时间内按下按键
  169. else if (((TimeSpan)(DateTime.Now - _last)).TotalMilliseconds < ts)
  170. {
  171. _keys[_keys.Count - 1].Add(msg);
  172. }
  173. // 从新记录输入内容
  174. else
  175. {
  176. _keys.Add(new List<EventMsg>());
  177. _keys[_keys.Count - 1].Add(msg);
  178. _result.Add(string.Empty);
  179. }
  180. #endregion
  181. _last = DateTime.Now;
  182. #region 获取键盘状态
  183. // 记录正在按下的按键
  184. if (msg.paramH == 0 && !_keydown.Contains(msg.message))
  185. {
  186. _keydown.Add(msg.message);
  187. }
  188. // 清除已松开的按键
  189. if (msg.paramH > 0 && _keydown.Contains(msg.message))
  190. {
  191. _keydown.Remove(msg.message);
  192. }
  193. #endregion
  194. #region 计算按键信息
  195. int v = msg.message & 0xff;
  196. int c = msg.paramL & 0xff;
  197. StringBuilder strKeyName = new StringBuilder(500);
  198. if (GetKeyNameText(c * 65536, strKeyName, 255) > 0)
  199. {
  200. _key = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
  201. GetKeyboardState(_state);
  202. if (_key.Length == 1 && msg.paramH == 0)
  203. {
  204. // 根据键盘状态和shift缓存判断输出字符
  205. _cur = ShiftChar(_key, isShift, _state).ToString();
  206. _result[_result.Count - 1] += _cur;
  207. }
  208. else
  209. {
  210. _cur = string.Empty;
  211. }
  212. }
  213. #endregion
  214. }
  215. private char ShiftChar(string k, bool isShiftDown, byte[] state)
  216. {
  217. bool capslock = state[0x14] == 1;
  218. bool numlock = state[0x90] == 1;
  219. bool scrolllock = state[0x91] == 1;
  220. bool shiftdown = state[0xa0] == 1;
  221. char chr = (capslock ? k.ToUpper() : k.ToLower()).ToCharArray()[0];
  222. if (isShiftDown)
  223. {
  224. if (chr >= 'a' && chr <= 'z')
  225. {
  226. chr = (char)((int)chr - 32);
  227. }
  228. else if (chr >= 'A' && chr <= 'Z')
  229. {
  230. chr = (char)((int)chr + 32);
  231. }
  232. else
  233. {
  234. string s = "`1234567890-=[];',./";
  235. string u = "~!@#$%^&*()_+{}:\"<>?";
  236. if (s.IndexOf(chr) >= 0)
  237. {
  238. return (u.ToCharArray())[s.IndexOf(chr)];
  239. }
  240. }
  241. }
  242. return chr;
  243. }
  244. }
  245. public struct EventMsg
  246. {
  247. public int message;
  248. public int paramL;
  249. public int paramH;
  250. public int Time;
  251. public int hwnd;
  252. }
  253. }
  254. }