How to programmatically get the Device Instance ID (unique ID) of a USB mass storage device that a user just plugged in?
Asked
Active
Viewed 3,991 times
2 Answers
2
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
- 100,020
- 15
- 103
- 173
-
`lParam` of `WM_DEVICECHANGE`, may or may not be cast to `DBT_DEVTYP_DEVICEINTERFACE`. It depends on `wParam`. for eg. it can be cast if wparam is `DBT_DEVICEARRIVAL`, or `DBT_DEVICEREMOVECOMPLETE`, but not when it is `DBT_DEVNODES_CHANGED`. For the case of `DBT_DEVNODES_CHANGED` `lParam` is always `zero`. – Sahil Singh Oct 11 '17 at 12:16
1
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.

Hans Olsson
- 54,199
- 15
- 94
- 116
-
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 Jun 16 '10 at 08:18
-
@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 – Hans Olsson Jun 16 '10 at 08:37