private void Button_Click(object sender, RoutedEventArgs e) { CalibrationScanGun win = new CalibrationScanGun(); win.Owner = Window.GetWindow(sender as Button); //窗体关闭后,获取 ScanGun ID str_ScanGunID = win.ShowDialog(); //如果返回的ID有值,那么就保存 if (str_ScanGunID != string.Empty) { Properties.Settings.Default.MyScanGun = str_ScanGunID; Properties.Settings.Default.Save(); textBox_ScanGunInfoCali.Text = str_ScanGunID; } }
void ComponentDispatcher_ThreadFilterMessage(ref System.Windows.Interop.MSG msg, ref bool handled) { switch (msg.message) { //这里只能以 INPUT 来截取,不支持 KEYDOWN 来截取,不然后面的 RawInput 获取值的时候无效 case Win32.WM_INPUT: { // Should never get here if you are using PreMessageFiltering KeyPressEvent keyPressEvent; _keyboardDriver.ProcessRawInput(msg.lParam, out keyPressEvent); textBox_ScanGunInfoNow.Text = keyPressEvent.DeviceName; //只处理一次事件,不然有按下和弹起事件 if (keyPressEvent.KeyPressState == "MAKE" && keyPressEvent.DeviceName == str_ScanGunID && str_ScanGunID != string.Empty) { textBox_Output.Focus(); //找到结尾标志的时候,就不加入队列了,然后就发送到界面上赋值 if (KeyInterop.KeyFromVirtualKey(keyPressEvent.VKey) == Key.Enter) { _isMonitoring = false; string str_Out = string.Empty; ThreadPool.QueueUserWorkItem((o) => { while (_eventQ.Count > 0) { RawInput_dll.Win32.KeyAndState keyAndState = _eventQ.Dequeue(); str_Out += CalibrationScanGun.Chr(keyAndState.Key).ToString(); System.Threading.Thread.Sleep(5); // might need adjustment } Application.Current.Dispatcher.BeginInvoke((Action)(() => { textBox_Output.Text = str_Out; })); _eventQ.Clear(); _isMonitoring = true; }); } // 回车 作为结束标志 if (_isMonitoring) { //存储 Win32 按键的int值 int key = keyPressEvent.VKey; byte[] state = new byte[256]; Win32.GetKeyboardState(state); _eventQ.Enqueue(new RawInput_dll.Win32.KeyAndState(key, state)); } } } break; case Win32.WM_KEYDOWN: { KeyPressEvent keyPressEvent; _keyboardDriver.ProcessRawInput(msg.lParam, out keyPressEvent); if (keyPressEvent.DeviceName == str_ScanGunID && str_ScanGunID != string.Empty) { handled = true; } } break; //这里截获这个消息有问题,替代方法是放到 WndProc 中去获取 case Win32.WM_USB_DEVICECHANGE: { } break; default: break; } return; }