1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public MainWindow() { Loaded+=MainWindow_Loaded; }
void MainWindow_Loaded(object sender,RoutedEventArgs e) { HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource; if(null!=hwndSource) hwndSource.AddHook(new HwndSourceHook(DevieceChanged)); }
private IntPtr DeviceChanged(IntPtr hwnd,int msg,IntPtr wParam,IntPtr lParam,ref bool handled) { string[] PortNames; if (msg == WM_DEVICECHANGE) { switch (wParam.ToInt32()) { case DBT_DEVICEARRIVAL: PortNames = SerialPort.GetPortNames(); if (IsWorking == true && PortNames.Contains(ConfigInfo.Port)) { if (serialPortUtil != null) { serialPortUtil.OpenPort(); MsgBox.Show("串口连接成功!"); } } break; case DBT_DEVICEREMOVECOMPLETE: PortNames = SerialPort.GetPortNames(); if (IsWorking == true && !PortNames.Contains(ConfigInfo.Port)) { MsgBox.Show("串口连接断开!"); } break; default: break; } } return IntPtr.Zero; }
|