views:

1129

answers:

3

I have a c# winforms program and it opens up a serial port. The problem happens when the end user unplugs the usb cable and then the device disappears. After this the program will crash and want to report the error to microsoft.

Is there a way to capture this event and shut down gracefully?

A: 

If your try statement isn't catching the exception then let's hope Microsoft will inspect the dumps.

There are some SetupDi APIs (I think ... it's been a while) that permit you to be advised of device arrivals and removals, but it won't help if you already crashed because the removed device was in the middle of your read or write operation.

Windows programmer
+1  A: 

Yes, there is a way to capture the event. Unfortunately, there can be a long delay between the time the device is removed and the time the program receives any notification.

The approach is to trap com port events such as ErrorReceived and to catch the WM_DEVICECHANGE message.

Not sure why your program is crashing; you should take a look at the stack to see where this is happening.

jdigital
+2  A: 

In registry at:
HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
is actual list of ports. If your port disappeared it means it was unplugged.

Real example: (Try to remove your USB and press F5 in registry editor)

Windows Registry Editor Version 5.00
HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM]
"Winachsf0"="COM10"
"\\Device\\mxuport0"="COM1"
"\\Device\\Serial2"="COM13"

COM10 - My fax modem
COM1 - USB - moxa usb serial converter
COM13 - USB - Profilic serial converter

Regards

MarekK