Class1.cs 8.9 KB

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