Customer request without manually close a serial port, pull the hardware, the software on the computer can timely response to, my train of thought is in the device plug change function retrieves a serial port. SerialPort GetPortNames (), access to the list of serial port and just open the serial port, if there is no open the serial port is pulled out just now, but pulled out after the hardware SerialPort. GetPortNames () to obtain a list of and unplug your serial number, ask the great spirit action, how can get to pull a serial port, and then the response to the interface
HwndSource HwndSource=PresentationSource. FromVisual (this) as HwndSource;//window procedure If (hwndSource!=null) HwndSource. AddHook (new HwndSourceHook (DeveiceChanged));//peg
//device plug change function Private IntPtr DeveiceChanged (IntPtr HWND, int MSG, IntPtr wParam, IntPtr lParam, ref bool handled) { String [] PortNames; If (MSG==WM_DEVICECHANGE) { If (ComPortIsOpen) { PortNames=SerialPort. GetPortNames (); if (! PortNames. The Contains (ComPort. PortName)) { SetAfterClose (); } } } Return IntPtr. Zero; }
CodePudding user response:
WqlEventQuery insertQuery=new WqlEventQuery (" SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub' ");
ManagementEventWatcher insertWatcher=new ManagementEventWatcher (insertQuery); InsertWatcher. EventArrived +=(s, e)=& gt; { Var STR=new StringBuilder (); STR. Append (insert "plant");
Var instance=(ManagementBaseObject) e.N ewEvent (" TargetInstance "); Var description=instance. The Properties (" description ");
STR. Append (description. The Name + "=" + description. Value);
Var deviceId=instance. The Properties (" deviceId "); STR. Append (deviceId. Name + "=" + deviceId. Value);
WqlEventQuery removeQuery=new WqlEventQuery (" SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub' "); ManagementEventWatcher removeWatcher=new ManagementEventWatcher (removeQuery); RemoveWatcher. EventArrived +=(s, e)=& gt; { Var STR=new StringBuilder (); STR. Append (remove the "plant");
Var instance=(ManagementBaseObject) e.N ewEvent (" TargetInstance "); Var description=instance. The Properties (" description ");
STR. Append (description. The Name + "=" + description. Value);
Var deviceId=instance. The Properties (" deviceId "); STR. Append (deviceId. Name + "=" + deviceId. Value);