Using WMI to Query for Currently Attached USB Device
-
I am writing an application wherein I need to scan the computer to see if either of two different USB devices are attached. The first device appears as a HID, and the second device appears as a virtual COM port. Which WMI classes should I be checking to see if each device is attached? I am using this for the HID:
m\_bstrScope = SysAllocString( \_T("root\\\\CIMV2") ); m\_bstrQuery = SysAllocString( \_T("SELECT PNPDeviceID FROM Win32\_PnPEntity") );
...and this for the virtual COM port device:
m\_bstrScope = SysAllocString( \_T("root\\\\CIMV2") ); m\_bstrQuery = SysAllocString( \_T("SELECT DeviceID,PNPDeviceID FROM Win32\_SerialPort") );
This pseudo code shows how my scanning algorithm works:
if ( ScanForDevice1() ) // HID attached { /\* Success \*/ } else if ( ScanForDevice2() ) // Virtual COM port device attached { /\* Success \*/ } else { /\* Fail \*/ }
This seems to work, except when I change which device is connected between running the application. If device 1 is found, the scan for device 2 is aborted; the scan for device 2 only occurs if device 1 is not found. What happens is this:
- The application is run with both devices attached to the system. Device 1 is found, as expected. The application exits.
- Device 1 is unplugged from the system.
- The application is run with only device 2 attached to the system. Oddly, device 1 is found, even though it is not attached. The application exits.
- Both devices are unplugged from the system.
- The application is run with no devices attached. No devices are found, as expected. The application exits.
- Only device 2 is plugged back into the system.
- The application is run with only device 2 attached. The application finds device 2, as expected.
My best guess is that I am querying the wrong class(es). Which classes should my application be checking? Or, is there something else that I should be doing? Thanks.