Reputation: 617
How to programmatically get the Device Instance ID (unique ID) of a USB mass storage device that a user just plugged in?
Upvotes: 4
Views: 4371
Reputation: 104464
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");
}
}
....
Upvotes: 2
Reputation: 55001
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.
Upvotes: 1