I am writing a C# .NET app that accesses an USB device which exposes a serial port interface. I am using the handy .NET SerialPort class, which works just fine.
My problem is that I need to catch the DBT_DEVICEQUERYREMOVE event, but I don’t get the event if I register using DBT_DEVTYP_DEVICEINTERFACE. I do get DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE, but no DBT_DEVICEQUERYREMOVE.
From my web research it seems that I need to register using DBT_DEVTYP_HANDLE, which requires a handle, such as that returned by CreateFile. Since the SerialPort class does not expose this handle, I’m wondering if there is some other way to get the handle (or some other way to get the event of interest).
I think you could use a bit of reflection to get the handle, I don’t know of a better way to get the handle that the .NET Framework is currently using. The
SerialPortuses an internal type calledSerialStream. This Stream has the handle you want. Since I don’t have a serial port to test on, this code is a bit of a guesswork:This will give you a
SafeFileHandle, which is a wrapper for handles. You could callDangerousGetHandleto get the actualIntPtr.This handle only has a valid value after you call
Openon the SerialPort, and becomes invalid when it’s disposed. You should check theIsInvalidandIsClosedvalues of the handle first before using DangerousGetHandle.