Obtaining a USB storage device instance identifier (unique identifier) ​​programmatically

How to programmatically obtain the device instance identifier (unique identifier) ​​of the USB storage device that the user has just connected?

+4
source share
2 answers

Call WM_DEVICECHANGE from any window handle, registering for device change notifications. Thus:

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); 

lParam WM_DEVICECHANGE can be passed to DBT_DEVTYP_DEVICEINTERFACE. Note. When you connect the device, you can receive several WM_DEVICECHANGE notifications. Just filter 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"); } } .... 
+2
source

I think you can do it using WMI. Look at the Win32_LogicalDiskToPartition class for a list of all drive names, and then use these names to query the Win32_DiskDrive class and its PNPDeviceID property.

Actually, look here for better instructions and a good class that will do this for you.

+1
source

Source: https://habr.com/ru/post/1312935/


All Articles