using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using BeiJingComService.Core; using BeiJingComService.Infrastructure; namespace BeiJingComService.WinForms { /// /// 扫码预捕获:低级键盘钩子旁听(Round54)。 /// /// 只做一件事:识别「扫码枪整串输入」,通过 交给业务侧取用。 /// /// 三条硬约束(改动前请先读): /// 1. 永远返回 CallNextHookEx 原值,不拦截、不吞键、不改写 —— 否则会拖累输入法、 /// 远程桌面以及其他程序的按键分发; /// 2. 回调内零 I/O(不写日志、不发 HTTP、不碰文件)。低级键盘钩子是串行的, /// 系统要等回调返回才把按键分发出去;回调超过 LowLevelHooksTimeout(默认 300ms) /// 会拖慢整机键盘,随后被系统静默摘钩且不通知,表现为「用着用着就不灵了」; /// 3. 钩子必须装在有消息泵的线程上(本程序是 Main 线程 + Application.Run)。 /// --service 模式跑在 Session 0,没有交互桌面也没有消息泵,钩子收不到按键。 /// internal static class ScanWatcher { private const int WH_KEYBOARD_LL = 13; private const int WM_KEYDOWN = 0x0100; private const int WM_SYSKEYDOWN = 0x0104; private const int VK_TAB = 0x09; private const int VK_RETURN = 0x0D; private const int VK_SHIFT = 0x10; private const int VK_CONTROL = 0x11; private const int VK_MENU = 0x12; // Alt private const int VK_CAPITAL = 0x14; private const int VK_ESCAPE = 0x1B; private const int VK_PRIOR = 0x21; // PageUp private const int VK_NEXT = 0x22; // PageDown private const int VK_END = 0x23; private const int VK_HOME = 0x24; private const int VK_LEFT = 0x25; private const int VK_UP = 0x26; private const int VK_RIGHT = 0x27; private const int VK_DOWN = 0x28; private const int VK_INSERT = 0x2D; private const int VK_DELETE = 0x2E; private const int VK_LWIN = 0x5B; private const int VK_RWIN = 0x5C; private const int VK_LSHIFT = 0xA0; private const int VK_RSHIFT = 0xA1; private const uint MAPVK_VK_TO_CHAR = 2; private const int MAX_SCAN_LENGTH = 1024; private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam); [StructLayout(LayoutKind.Sequential)] private struct KBDLLHOOKSTRUCT { public uint vkCode; public uint scanCode; public uint flags; public uint time; public IntPtr dwExtraInfo; } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetKeyboardState(byte[] lpKeyState); [DllImport("user32.dll")] private static extern int ToUnicodeEx(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszBuff, int cchBuff, uint wFlags, IntPtr dwhkl); [DllImport("user32.dll")] private static extern IntPtr GetKeyboardLayout(uint idThread); [DllImport("user32.dll")] private static extern uint MapVirtualKey(uint uCode, uint uMapType); // ===== 必须保留委托的静态引用:被 GC 回收后原生侧回调即崩溃 ===== private static LowLevelKeyboardProc _proc; private static IntPtr _hook = IntPtr.Zero; // ===== 拼串状态(只在钩子回调所在线程访问,无需加锁)===== private static readonly StringBuilder _sb = new StringBuilder(MAX_SCAN_LENGTH + 8); private static long _firstKeyMs; private static long _lastKeyMs; /// 钩子是否已装上。 internal static bool IsRunning { get { return _hook != IntPtr.Zero; } } /// 最近一次成功捕获的时刻(毫秒时间源)。只用于诊断「钩子还活着吗」,不含码内容。 internal static long LastCaptureMs { get; private set; } /// 成功捕获次数(诊断用)。 internal static int CaptureCount { get; private set; } internal static void Start() { if (_hook != IntPtr.Zero) { return; } if (!AppConfig.ScanCaptureEnabled) { Logger.Info("[扫码预捕获] 配置关闭(ScanCaptureEnabled=false),不装键盘钩子"); return; } try { _proc = HookProc; // 先给静态字段赋值,防 GC IntPtr hMod = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName); _hook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, hMod, 0); if (_hook == IntPtr.Zero) { int err = Marshal.GetLastWin32Error(); Logger.Error("[扫码预捕获] 键盘钩子安装失败,Win32 错误码 " + err + "(功能不生效,业务侧会自动降级为原弹框流程)"); _proc = null; return; } Logger.Info("[扫码预捕获] 键盘钩子已加载,TTL=" + ScanBuffer.TtlMs + "ms" + ",判定阈值 时长<=" + AppConfig.ScanCaptureMaxDurationMs + "ms" + " 间隔<=" + AppConfig.ScanCaptureMaxKeyGapMs + "ms" + " 长度>=" + AppConfig.ScanCaptureMinLength); } catch (Exception ex) { Logger.Error("[扫码预捕获] 键盘钩子安装异常,功能不生效", ex); _hook = IntPtr.Zero; _proc = null; } } internal static void Stop() { try { if (_hook == IntPtr.Zero) { return; } UnhookWindowsHookEx(_hook); _hook = IntPtr.Zero; _proc = null; Reset(); Logger.Info("[扫码预捕获] 键盘钩子已卸载"); } catch (Exception ex) { Logger.Error("[扫码预捕获] 卸载键盘钩子异常", ex); _hook = IntPtr.Zero; _proc = null; } } private static IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0) { try { int msg = wParam.ToInt32(); if (msg == WM_SYSKEYDOWN) { // Alt 组合键,不可能是扫码枪输出 Reset(); } else if (msg == WM_KEYDOWN) { KBDLLHOOKSTRUCT info = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure( lParam, typeof(KBDLLHOOKSTRUCT)); HandleKey(info.vkCode, info.scanCode); } } catch { // 回调里绝不能把异常抛回原生侧,否则整个进程直接崩 Reset(); } } // 永远透传:不拦截、不吞键 return CallNextHookEx(_hook, nCode, wParam, lParam); } private static void HandleKey(uint vk, uint scanCode) { long now = ScanBuffer.NowMs(); // ① 修饰键:Shift 必须放过(扫码枪输出大写字母时会按住 Shift), // CapsLock 同理;它们不产生字符,不参与拼串,也不刷新时间戳。 if (vk == VK_SHIFT || vk == VK_LSHIFT || vk == VK_RSHIFT || vk == VK_CAPITAL) { return; } // ② 这些键一出现就说明不是扫码枪整串输入,清空重来 if (IsResetKey(vk)) { Reset(); return; } // ③ 回车 / Tab = 扫码枪输出结束。 // 现场扫码枪的后缀可能是 CR(回车),也可能是 Tab,两种都必须认, // 否则某些机型会把整串丢掉(表现为「钩子装了却一个码都抓不到」)。 // 人工按 Tab 不会误命中:长度判定之外还有 300ms 总时长闸,人敲 8 个字符做不到。 if (vk == VK_RETURN || vk == VK_TAB) { if (_sb.Length >= AppConfig.ScanCaptureMinLength) { long duration = now - _firstKeyMs; if (duration >= 0 && duration <= AppConfig.ScanCaptureMaxDurationMs) { ScanBuffer.Push(_sb.ToString(), now); LastCaptureMs = now; CaptureCount++; } } Reset(); return; } // ④ 相邻字符间隔过大 → 人工输入,清空重来 if (_sb.Length > 0 && (now - _lastKeyMs) > AppConfig.ScanCaptureMaxKeyGapMs) { Reset(); } char ch = VkToChar(vk, scanCode); if (ch == '\0') { // 转不出可打印字符(功能键、输入法拦截等),视为非扫码枪输入 Reset(); return; } if (_sb.Length == 0) { _firstKeyMs = now; } _lastKeyMs = now; _sb.Append(ch); if (_sb.Length > MAX_SCAN_LENGTH) { Reset(); } } private static bool IsResetKey(uint vk) { // 注意:不包含 VK_TAB —— Tab 在 HandleKey 里当扫码结束符处理 if (vk == VK_ESCAPE) { return true; } if (vk == VK_CONTROL || vk == VK_MENU || vk == VK_LWIN || vk == VK_RWIN) { return true; } if (vk >= 0x70 && vk <= 0x87) { return true; } // F1~F24 if (vk == VK_PRIOR || vk == VK_NEXT || vk == VK_END || vk == VK_HOME) { return true; } if (vk == VK_LEFT || vk == VK_UP || vk == VK_RIGHT || vk == VK_DOWN) { return true; } if (vk == VK_INSERT || vk == VK_DELETE) { return true; } return false; } /// /// 虚拟键码 → 可打印字符。 /// 必须走 ToUnicodeEx:医保电子凭证码是 Base64 风格内容,大小写敏感, /// 用 MapVirtualKey 只能得到大写,a/A 分不清,整串码就废了。 /// private static char VkToChar(uint vk, uint scanCode) { try { byte[] keyState = new byte[256]; if (!GetKeyboardState(keyState)) { return '\0'; } StringBuilder buf = new StringBuilder(4); int rc = ToUnicodeEx(vk, scanCode, keyState, buf, buf.Capacity, 0, GetKeyboardLayout(0)); if (rc > 0 && buf.Length > 0) { char c = buf[0]; return (c >= 0x20 && c <= 0x7E) ? c : '\0'; } // 回退:部分输入法状态下 ToUnicodeEx 返回 0,用 MapVirtualKey 兜底 if (rc == 0) { uint mapped = MapVirtualKey(vk, MAPVK_VK_TO_CHAR); char mc = (char)(mapped & 0xFFFF); if (mc >= 0x20 && mc <= 0x7E) { return mc; } } } catch { // 回调内吞掉一切异常 } return '\0'; } private static void Reset() { _sb.Length = 0; _firstKeyMs = 0; _lastKeyMs = 0; } } }