ScanWatcher.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. using BeiJingComService.Core;
  6. using BeiJingComService.Infrastructure;
  7. namespace BeiJingComService.WinForms
  8. {
  9. /// <summary>
  10. /// 扫码预捕获:低级键盘钩子旁听(Round54)。
  11. ///
  12. /// 只做一件事:识别「扫码枪整串输入」,通过 <see cref="ScanBuffer"/> 交给业务侧取用。
  13. ///
  14. /// 三条硬约束(改动前请先读):
  15. /// 1. 永远返回 CallNextHookEx 原值,<b>不拦截、不吞键、不改写</b> —— 否则会拖累输入法、
  16. /// 远程桌面以及其他程序的按键分发;
  17. /// 2. 回调内<b>零 I/O</b>(不写日志、不发 HTTP、不碰文件)。低级键盘钩子是串行的,
  18. /// 系统要等回调返回才把按键分发出去;回调超过 LowLevelHooksTimeout(默认 300ms)
  19. /// 会拖慢整机键盘,随后被系统静默摘钩且不通知,表现为「用着用着就不灵了」;
  20. /// 3. 钩子必须装在<b>有消息泵的线程</b>上(本程序是 Main 线程 + Application.Run)。
  21. /// --service 模式跑在 Session 0,没有交互桌面也没有消息泵,钩子收不到按键。
  22. /// </summary>
  23. internal static class ScanWatcher
  24. {
  25. private const int WH_KEYBOARD_LL = 13;
  26. private const int WM_KEYDOWN = 0x0100;
  27. private const int WM_SYSKEYDOWN = 0x0104;
  28. private const int VK_TAB = 0x09;
  29. private const int VK_RETURN = 0x0D;
  30. private const int VK_SHIFT = 0x10;
  31. private const int VK_CONTROL = 0x11;
  32. private const int VK_MENU = 0x12; // Alt
  33. private const int VK_CAPITAL = 0x14;
  34. private const int VK_ESCAPE = 0x1B;
  35. private const int VK_PRIOR = 0x21; // PageUp
  36. private const int VK_NEXT = 0x22; // PageDown
  37. private const int VK_END = 0x23;
  38. private const int VK_HOME = 0x24;
  39. private const int VK_LEFT = 0x25;
  40. private const int VK_UP = 0x26;
  41. private const int VK_RIGHT = 0x27;
  42. private const int VK_DOWN = 0x28;
  43. private const int VK_INSERT = 0x2D;
  44. private const int VK_DELETE = 0x2E;
  45. private const int VK_LWIN = 0x5B;
  46. private const int VK_RWIN = 0x5C;
  47. private const int VK_LSHIFT = 0xA0;
  48. private const int VK_RSHIFT = 0xA1;
  49. private const uint MAPVK_VK_TO_CHAR = 2;
  50. private const int MAX_SCAN_LENGTH = 1024;
  51. private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
  52. [StructLayout(LayoutKind.Sequential)]
  53. private struct KBDLLHOOKSTRUCT
  54. {
  55. public uint vkCode;
  56. public uint scanCode;
  57. public uint flags;
  58. public uint time;
  59. public IntPtr dwExtraInfo;
  60. }
  61. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  62. private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
  63. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  64. [return: MarshalAs(UnmanagedType.Bool)]
  65. private static extern bool UnhookWindowsHookEx(IntPtr hhk);
  66. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  67. private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
  68. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  69. private static extern IntPtr GetModuleHandle(string lpModuleName);
  70. [DllImport("user32.dll")]
  71. [return: MarshalAs(UnmanagedType.Bool)]
  72. private static extern bool GetKeyboardState(byte[] lpKeyState);
  73. [DllImport("user32.dll")]
  74. private static extern int ToUnicodeEx(uint wVirtKey, uint wScanCode, byte[] lpKeyState,
  75. [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszBuff,
  76. int cchBuff, uint wFlags, IntPtr dwhkl);
  77. [DllImport("user32.dll")]
  78. private static extern IntPtr GetKeyboardLayout(uint idThread);
  79. [DllImport("user32.dll")]
  80. private static extern uint MapVirtualKey(uint uCode, uint uMapType);
  81. // ===== 必须保留委托的静态引用:被 GC 回收后原生侧回调即崩溃 =====
  82. private static LowLevelKeyboardProc _proc;
  83. private static IntPtr _hook = IntPtr.Zero;
  84. // ===== 拼串状态(只在钩子回调所在线程访问,无需加锁)=====
  85. private static readonly StringBuilder _sb = new StringBuilder(MAX_SCAN_LENGTH + 8);
  86. private static long _firstKeyMs;
  87. private static long _lastKeyMs;
  88. /// <summary>钩子是否已装上。</summary>
  89. internal static bool IsRunning
  90. {
  91. get { return _hook != IntPtr.Zero; }
  92. }
  93. /// <summary>最近一次成功捕获的时刻(毫秒时间源)。只用于诊断「钩子还活着吗」,不含码内容。</summary>
  94. internal static long LastCaptureMs { get; private set; }
  95. /// <summary>成功捕获次数(诊断用)。</summary>
  96. internal static int CaptureCount { get; private set; }
  97. internal static void Start()
  98. {
  99. if (_hook != IntPtr.Zero) { return; }
  100. if (!AppConfig.ScanCaptureEnabled)
  101. {
  102. Logger.Info("[扫码预捕获] 配置关闭(ScanCaptureEnabled=false),不装键盘钩子");
  103. return;
  104. }
  105. try
  106. {
  107. _proc = HookProc; // 先给静态字段赋值,防 GC
  108. IntPtr hMod = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
  109. _hook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, hMod, 0);
  110. if (_hook == IntPtr.Zero)
  111. {
  112. int err = Marshal.GetLastWin32Error();
  113. Logger.Error("[扫码预捕获] 键盘钩子安装失败,Win32 错误码 " + err
  114. + "(功能不生效,业务侧会自动降级为原弹框流程)");
  115. _proc = null;
  116. return;
  117. }
  118. Logger.Info("[扫码预捕获] 键盘钩子已加载,TTL=" + ScanBuffer.TtlMs + "ms"
  119. + ",判定阈值 时长<=" + AppConfig.ScanCaptureMaxDurationMs + "ms"
  120. + " 间隔<=" + AppConfig.ScanCaptureMaxKeyGapMs + "ms"
  121. + " 长度>=" + AppConfig.ScanCaptureMinLength);
  122. }
  123. catch (Exception ex)
  124. {
  125. Logger.Error("[扫码预捕获] 键盘钩子安装异常,功能不生效", ex);
  126. _hook = IntPtr.Zero;
  127. _proc = null;
  128. }
  129. }
  130. internal static void Stop()
  131. {
  132. try
  133. {
  134. if (_hook == IntPtr.Zero) { return; }
  135. UnhookWindowsHookEx(_hook);
  136. _hook = IntPtr.Zero;
  137. _proc = null;
  138. Reset();
  139. Logger.Info("[扫码预捕获] 键盘钩子已卸载");
  140. }
  141. catch (Exception ex)
  142. {
  143. Logger.Error("[扫码预捕获] 卸载键盘钩子异常", ex);
  144. _hook = IntPtr.Zero;
  145. _proc = null;
  146. }
  147. }
  148. private static IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam)
  149. {
  150. if (nCode >= 0)
  151. {
  152. try
  153. {
  154. int msg = wParam.ToInt32();
  155. if (msg == WM_SYSKEYDOWN)
  156. {
  157. // Alt 组合键,不可能是扫码枪输出
  158. Reset();
  159. }
  160. else if (msg == WM_KEYDOWN)
  161. {
  162. KBDLLHOOKSTRUCT info = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(
  163. lParam, typeof(KBDLLHOOKSTRUCT));
  164. HandleKey(info.vkCode, info.scanCode);
  165. }
  166. }
  167. catch
  168. {
  169. // 回调里绝不能把异常抛回原生侧,否则整个进程直接崩
  170. Reset();
  171. }
  172. }
  173. // 永远透传:不拦截、不吞键
  174. return CallNextHookEx(_hook, nCode, wParam, lParam);
  175. }
  176. private static void HandleKey(uint vk, uint scanCode)
  177. {
  178. long now = ScanBuffer.NowMs();
  179. // ① 修饰键:Shift 必须放过(扫码枪输出大写字母时会按住 Shift),
  180. // CapsLock 同理;它们不产生字符,不参与拼串,也不刷新时间戳。
  181. if (vk == VK_SHIFT || vk == VK_LSHIFT || vk == VK_RSHIFT || vk == VK_CAPITAL)
  182. {
  183. return;
  184. }
  185. // ② 这些键一出现就说明不是扫码枪整串输入,清空重来
  186. if (IsResetKey(vk))
  187. {
  188. Reset();
  189. return;
  190. }
  191. // ③ 回车 / Tab = 扫码枪输出结束。
  192. // 现场扫码枪的后缀可能是 CR(回车),也可能是 Tab,两种都必须认,
  193. // 否则某些机型会把整串丢掉(表现为「钩子装了却一个码都抓不到」)。
  194. // 人工按 Tab 不会误命中:长度判定之外还有 300ms 总时长闸,人敲 8 个字符做不到。
  195. if (vk == VK_RETURN || vk == VK_TAB)
  196. {
  197. if (_sb.Length >= AppConfig.ScanCaptureMinLength)
  198. {
  199. long duration = now - _firstKeyMs;
  200. if (duration >= 0 && duration <= AppConfig.ScanCaptureMaxDurationMs)
  201. {
  202. ScanBuffer.Push(_sb.ToString(), now);
  203. LastCaptureMs = now;
  204. CaptureCount++;
  205. }
  206. }
  207. Reset();
  208. return;
  209. }
  210. // ④ 相邻字符间隔过大 → 人工输入,清空重来
  211. if (_sb.Length > 0 && (now - _lastKeyMs) > AppConfig.ScanCaptureMaxKeyGapMs)
  212. {
  213. Reset();
  214. }
  215. char ch = VkToChar(vk, scanCode);
  216. if (ch == '\0')
  217. {
  218. // 转不出可打印字符(功能键、输入法拦截等),视为非扫码枪输入
  219. Reset();
  220. return;
  221. }
  222. if (_sb.Length == 0) { _firstKeyMs = now; }
  223. _lastKeyMs = now;
  224. _sb.Append(ch);
  225. if (_sb.Length > MAX_SCAN_LENGTH) { Reset(); }
  226. }
  227. private static bool IsResetKey(uint vk)
  228. {
  229. // 注意:不包含 VK_TAB —— Tab 在 HandleKey 里当扫码结束符处理
  230. if (vk == VK_ESCAPE) { return true; }
  231. if (vk == VK_CONTROL || vk == VK_MENU || vk == VK_LWIN || vk == VK_RWIN) { return true; }
  232. if (vk >= 0x70 && vk <= 0x87) { return true; } // F1~F24
  233. if (vk == VK_PRIOR || vk == VK_NEXT || vk == VK_END || vk == VK_HOME) { return true; }
  234. if (vk == VK_LEFT || vk == VK_UP || vk == VK_RIGHT || vk == VK_DOWN) { return true; }
  235. if (vk == VK_INSERT || vk == VK_DELETE) { return true; }
  236. return false;
  237. }
  238. /// <summary>
  239. /// 虚拟键码 → 可打印字符。
  240. /// 必须走 ToUnicodeEx:医保电子凭证码是 Base64 风格内容,<b>大小写敏感</b>,
  241. /// 用 MapVirtualKey 只能得到大写,a/A 分不清,整串码就废了。
  242. /// </summary>
  243. private static char VkToChar(uint vk, uint scanCode)
  244. {
  245. try
  246. {
  247. byte[] keyState = new byte[256];
  248. if (!GetKeyboardState(keyState)) { return '\0'; }
  249. StringBuilder buf = new StringBuilder(4);
  250. int rc = ToUnicodeEx(vk, scanCode, keyState, buf, buf.Capacity, 0, GetKeyboardLayout(0));
  251. if (rc > 0 && buf.Length > 0)
  252. {
  253. char c = buf[0];
  254. return (c >= 0x20 && c <= 0x7E) ? c : '\0';
  255. }
  256. // 回退:部分输入法状态下 ToUnicodeEx 返回 0,用 MapVirtualKey 兜底
  257. if (rc == 0)
  258. {
  259. uint mapped = MapVirtualKey(vk, MAPVK_VK_TO_CHAR);
  260. char mc = (char)(mapped & 0xFFFF);
  261. if (mc >= 0x20 && mc <= 0x7E) { return mc; }
  262. }
  263. }
  264. catch
  265. {
  266. // 回调内吞掉一切异常
  267. }
  268. return '\0';
  269. }
  270. private static void Reset()
  271. {
  272. _sb.Length = 0;
  273. _firstKeyMs = 0;
  274. _lastKeyMs = 0;
  275. }
  276. }
  277. }