7

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?

3
  • Had this problem too a long time ago and couldn't find a way to prevent the crash. Curious if someone came up with a way in the meantime, in my case I just left that as a wide open known issue.
    – Alex Paven
    Mar 10, 2011 at 20:54
  • I believe that the "crashing" problem has been fixed in .Net 4.0. Once the port is unplugged any attempt to use the port should throw an error that can be caught.
    – dbasnett
    Mar 12, 2011 at 13:55
  • We had many issues with the SerialPort class and switched to SuperCom (see adontec.com). The SuperCom NET library solved many issues. It also offers an OnPlug event when USB serial ports appear/disappear.
    – lindev
    Sep 10, 2019 at 13:53

6 Answers 6

8

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.

5
+25

You can use WMI (Windows Management Instrumentation) to receive notification on USB events. I did exactly that two years ago, monitoring for plugging and unplugging of a specific usb device.
Unfortunately, the code stays with my former employer, but I found one example at bytes.com:

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Management;
class UsbWatcher 
{
    public static void Main() 
    {
        WMIEvent wEvent = new WMIEvent();
        ManagementEventWatcher watcher = null;
        WqlEventQuery query;
        ManagementOperationObserver observer = new ManagementOperationObserver();

        ManagementScope scope = new ManagementScope("root\\CIMV2");
        scope.Options.EnablePrivileges = true; 
        try 
        {
            query = new WqlEventQuery();
            query.EventClassName = "__InstanceCreationEvent";
            query.WithinInterval = new TimeSpan(0,0,10);

            query.Condition = @"TargetInstance ISA 'Win32_USBControllerDevice' ";
            watcher = new ManagementEventWatcher(scope, query);

            watcher.EventArrived 
                += new EventArrivedEventHandler(wEvent.UsbEventArrived);
            watcher.Start();
        }
        catch (Exception e)
        {
            //handle exception
        }
}

I don't remember if I modified the query to receive events only for e specific device, or if I filtered out events from other devices in my event handler. For further information you may want to have a look at the MSDN WMI .NET Code Directory.

EDIT I found some more info on the event handler, it looks roughly like this:

protected virtual void OnUsbConnected(object Sender, EventArrivedEventArgs Arguments)
{
    PropertyData TargetInstanceData = Arguments.NewEvent.Properties["TargetInstance"];

    if (TargetInstanceData != null)
    {
        ManagementBaseObject TargetInstanceObject = (ManagementBaseObject)TargetInstanceData.Value;
        if (TargetInstanceObject != null)
        {
            string dependent = TargetInstanceObject.Properties["Dependent"].Value.ToString();
            string deviceId = dependent.Substring(dependent.IndexOf("DeviceID=") + 10);

            // device id string taken from windows device manager
            if (deviceId = "USB\\\\VID_0403&PID_6001\\\\12345678\"")
            {
                // Device is connected
            }
        }
    }
}

You may want to add some exception handling, though.

3

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

1
  • As COM10 - My fax modem then "Winachsf0"="COM10" is fax modem driver, isn't?
    – MrHIDEn
    Mar 25, 2021 at 11:22
2

Although the answers already given provide a good starting point, I would like to add some working examples for .net 4.5 and also an example of capturing a type of usb device.

In Treb's answer, he used the 'Win32_USBControllerDevice'. This may or may not be the best condition for your query, depending on what you want to accomplish. The device id from the Win32_USBControllerDevice is unique to each device. So if you're looking for a unique id that identifies a single device, then that's exactly what you want. But if you're looking for a certain type of device, you could use 'Win32_PnPEntity' and access the Description property. Here is an example of getting a certain type of device by its description:

using System;
using System.ComponentModel.Composition;
using System.Management;

public class UsbDeviceMonitor
{
    private ManagementEventWatcher plugInWatcher;
    private ManagementEventWatcher unPlugWatcher;
    private const string MyDeviceDescription = @"My Device Description";

    ~UsbDeviceMonitor()
    {
        Dispose();
    }

    public void Dispose()
    {
        if (plugInWatcher != null)
            try
            {
                plugInWatcher.Dispose();
                plugInWatcher = null;
            }
            catch (Exception) { }

        if (unPlugWatcher == null) return;
        try
        {
            unPlugWatcher.Dispose();
            unPlugWatcher = null;
        }
        catch (Exception) { }
    }

    public void Start()
    {
        const string plugInSql = "SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'";
        const string unpluggedSql = "SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'";

        var scope = new ManagementScope("root\\CIMV2") {Options = {EnablePrivileges = true}};

        var pluggedInQuery = new WqlEventQuery(plugInSql);
        plugInWatcher = new ManagementEventWatcher(scope, pluggedInQuery);
        plugInWatcher.EventArrived += HandlePluggedInEvent;
        plugInWatcher.Start();

        var unPluggedQuery = new WqlEventQuery(unpluggedSql);
        unPlugWatcher = new ManagementEventWatcher(scope, unPluggedQuery);
        unPlugWatcher.EventArrived += HandleUnPluggedEvent;
        unPlugWatcher.Start();
    }

    private void HandleUnPluggedEvent(object sender, EventArrivedEventArgs e)
    {
        var description = GetDeviceDescription(e.NewEvent);
        if (description.Equals(MyDeviceDescription))
            // Take actions here when the device is unplugged
    }

    private void HandlePluggedInEvent(object sender, EventArrivedEventArgs e)
    {
        var description = GetDeviceDescription(e.NewEvent);
        if (description.Equals(MyDeviceDescription))
            // Take actions here when the device is plugged in
    }

    private static string GetDeviceDescription(ManagementBaseObject newEvent)
    {
        var targetInstanceData = newEvent.Properties["TargetInstance"];
        var targetInstanceObject = (ManagementBaseObject) targetInstanceData.Value;
        if (targetInstanceObject == null) return "";

        var description = targetInstanceObject.Properties["Description"].Value.ToString();
        return description;
    }
}

Some links that might be useful for researching which classes to use in your sql statements:

Win32 Classes - In the example above, the 'Win32_PnPEntity' class was used.

WMI System Classes - In the example above, the __InstanceCreationEvent and __InstanceDeletionEvent classes were used.

1

You could try to handle ErrorReceived.

private void buttonStart_Click(object sender, EventArgs e)
{
    port.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(port_ErrorReceived);
}

void port_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
{
    // TODO: handle the problem here
}

Additionally, you could check whether the port exists before proceeding. You may want to check it once in a while, maybe just before reading/writing.

string[] ports = System.IO.Ports.SerialPort.GetPortNames();
if (ports.Contains("COM7:"))
{
    // TODO: Can continue
}
else
{
    // TODO: Cannot, terminate properly
}

You should also place try-catch blocks for all your serial port operations. It should help to prevent unexpected terminations.

You may want to try to run the app in debug mode under your IDE and simulate the error. If an exception is throw, you would be able to identify where the problem becomes most evident. From there, you could probably try to find more specific solutions.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.