private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam) { if (nCode == 0) { EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg)); if (wParam == 0x100) //WM_KEYDOWN = 0x100 { barCode.VirtKey = msg.message & 0xff; //虚拟码 barCode.ScanCode = msg.paramL & 0xff; //扫描码 StringBuilder strKeyName = new StringBuilder(255); if (GetKeyNameText(barCode.ScanCode * 65536, strKeyName, 255) > 0) { barCode.KeyName = strKeyName.ToString().Trim(new char[] { ' ', '0' }); } else { barCode.KeyName = string.Empty; } byte[] kbArray = new byte[256]; uint uKey = 0; GetKeyboardState(kbArray); if (ToAscii(barCode.VirtKey, barCode.ScanCode, kbArray, ref uKey, 0)) { barCode.AscII = uKey; barCode.Chr = Convert.ToChar(uKey); } if (DateTime.Now.Subtract(barCode.Time).TotalMilliseconds > 50) { strBarCode = barCode.Chr.ToString(); } else { if ((msg.message & 0xff) == 13 && strBarCode.Length > 3) //回车 { barCode.BarCode = strBarCode; barCode.IsValid = true; } strBarCode += barCode.Chr.ToString(); } barCode.Time = DateTime.Now; BarCodeEvent?.Invoke(barCode); //触发事件 barCode.IsValid = false; } } return(CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); }
private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam) { if (nCode != 0) { return(CallNextHookEx(_hKeyboardHook, nCode, wParam, lParam)); } var msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg)); if (wParam != 0x100) { return(CallNextHookEx(_hKeyboardHook, nCode, wParam, lParam)); } _barCode.VirtKey = msg.message & 0xff; //虚拟吗 _barCode.ScanCode = msg.paramL & 0xff; //扫描码 var strKeyName = new StringBuilder(225); _barCode.KeyName = GetKeyNameText(_barCode.ScanCode * 65536, strKeyName, 255) > 0 ? strKeyName.ToString().Trim(' ', '\0') : ""; var kbArray = new byte[256]; uint uKey = 0; GetKeyboardState(kbArray); if (ToAscii(_barCode.VirtKey, _barCode.ScanCode, kbArray, ref uKey, 0)) { _barCode.Ascll = uKey; _barCode.Chr = Convert.ToChar(uKey); } var ts = DateTime.Now.Subtract(_barCode.Time); if (ts.TotalMilliseconds > 50) {//时间戳,大于50 毫秒表示手动输入 _strBarCode = _barCode.Chr.ToString(); } else { if ((msg.message & 0xff) == 13 && _strBarCode.Length > 3) {//回车 _barCode.BarCode = _strBarCode; _barCode.IsValid = true; } _strBarCode += _barCode.Chr.ToString(); } _barCode.Time = DateTime.Now; BarCodeEvent?.Invoke(_barCode);//触发事件 _barCode.IsValid = false; return(CallNextHookEx(_hKeyboardHook, nCode, wParam, lParam)); }