views:

91

answers:

2

Whenever user plug a USB mass storage device, how to get the Device Instance ID (unique ID) of that particular device programmatically?

+1  A: 

I think you can do it using WMI. Look at the Win32_LogicalDiskToPartition class to get a list of all disk names and then use those names to query the class Win32_DiskDrive and it's PNPDeviceID property.

Actually, look here for better instructions and a nice class that does it for you.

ho1
But i want to find the device instance id of a newly plugged in device.At that time i dont know the Drive letter of that newly plugged device.And what if user is allready plugged two or three pen drive to the system and now he is inserting antoher device.
Navaneeth
@Navaneeth: Look at `ManagementEventWatcher` class and the 'DiskEventArrived' event. This code should show you the structure: http://www.eggheadcafe.com/software/aspnet/31850441/c-usb-pluginremoval-h.aspx
ho1
+1  A: 

Catch WM_DEVICECHANGE from any window handle by registering for device change notifications. As such:

DEV_BROADCAST_DEVICEINTERFACE dbd = { sizeof(dbd) };
dbd.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
dbd.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE;
RegisterDeviceNotification(hwnd, &dbd, DEVICE_NOTIFY_WINDOW_HANDLE);

The lParam of the WM_DEVICECHANGE can be cast to DBT_DEVTYP_DEVICEINTERFACE. Note - when plug in a device you may get multiple WM_DEVICECHANGE notifications. Just filter on the arrival event and ignore duplicates.

LRESULT WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(hwnd)
    {
        case WM_DEVICE_CHANGE:
        {
            PDEV_BROADCAST_HDR pHdr = NULL;
            PDEV_BROADCAST_DEVICEINTERFACE pDev = NULL;
            pHdr = (PDEV_BROADCAST_HDR)lParam;
            bool fDeviceArrival = (wParam == DBT_DEVICEARRIVAL);
            if (fDeviceArrival)
            {
                if (pHdr && (pHdr->dbch_devicetype==DBT_DEVTYP_DEVICEINTERFACE))
                {
                    pDev = (PDEV_BROADCAST_DEVICEINTERFACE)lParam;
                }
                if (pDev && (pDev->dbcc_classguid == GUID_DEVINTERFACE_USB_DEVICE))
                {
                    // the PNP string of the device just plugged is in dbcc_name
                    OutputDebugString(pDev->dbcc_name);
                    OutputDebugString("\r\n");
                }
            }
        ....
selbie