I'm using this(link) library to detect attach and detach events of USB devices. After detecting the right device attached(identified with specific VID/PID combination) I open a serial port connection and similarly when the device is detached I close the serial port connection.
My attach event works great and at the end I get a serial port that I can use but I'm having problems inside the detach event. The detach event fires correctly but when code execution reaches closeCOM(serialPort1)
point it jumps to wndProc
override loop and prevents execution of closeCOM()
and whatever follows.
The library needs WndProc
messages to detect the events and my code is implemented like this:
//Catch Windows messages and pass them to the USBClass class
protected override void WndProc(ref Message m)
{
USBPort.ProcessWindowsMessage(ref m);
base.WndProc(ref m);
}
Then I have a detach event which executes the following code:
if (!USBClass.GetUSBDevice(VID, PID, ref USBDeviceProperties, false) && USBDeviceConnected)
{
//Device is removed
USBDeviceConnected = false;
//Close COM port just in case we forgot to disconnect
closeCOM(serialPort1);
//update status strip
strip_device_status.Text = "Disconnected";
}
and here is the closeCOM
function:
//This function handles COM port closing.
private void closeCOM(SerialPort port)
{
// If a serial port is open, disconnect it
if (port.IsOpen)
{
// close the serial port
port.Close();
}
//update com port status flag
COMConnected = false;
//update status strip
strip_COM_status.Text = "Disconnected";
}
It is closeCOM()
in particular that's causing this "conflict" because if I comment out that line everything works, except I'm left with an open serial port possibly causing errors later on. What am I doing wrong that's causing the code to jump to WndProc
override instead of normal execution? I would like to be able to do the port closing in the detach event.