最近在開發USB相關的內容,在此記錄一下列舉USB設備的代碼(還可以列舉USB HUB)。
由於直接使用系統定義的GUID有問題,所以在頭文件中自己需要定義相關的GUID:
頭文件代碼如下(定義了USB DEVICE 和 USB HUB兩種的GUID,如果其他請看msdn):
#pragma once
#include "resource.h"
#include <stdio.h>
#include <windows.h>
#include <SetupAPI.h>
#include <iostream>
#include <Usbiodef.h>
#include <Usbioctl.h>
#include <devguid.h>
#include <winioctl.h>
#include <INITGUID.h>
#include <Dbt.h>
#include <map>
#include <wchar.h>
#pragma comment(lib, "Winmm.lib")
#pragma comment(lib, "setupapi.lib")
DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE,
0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED);
#define GUID_CLASS_USB_DEVICE GUID_DEVINTERFACE_USB_DEVICE
DEFINE_GUID(GUID_DEVINTERFACE_USB_HUB,
0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0xd8);
#define GUID_CLASS_USB_HUB GUID_DEVINTERFACE_USB_HUB
函數代碼如下,代碼中使用的GUID_CLASS_USB_HUB,可以用GUID_CLASS_USB_DEVICE來獲取連接的所有USB設備:
void getDevices()
{
LPGUID lpGuid = (LPGUID)&GUID_CLASS_USB_HUB;//
int INTERFACE_DETAIL_SIZE = 1024;
int nCount = 0;
HDEVINFO info = SetupDiGetClassDevs(lpGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
//enumerate device information
DWORD required_size = 0;
int i;
SP_DEVINFO_DATA DeviceInfoData = { sizeof(DeviceInfoData) };
DWORD DataT;
DWORD buffersize = 1024;
DWORD req_bufsize = 0;
for (i = 0; SetupDiEnumDeviceInfo(info, i, &DeviceInfoData); i++)
{
WCHAR *did = new WCHAR[1024];
WCHAR *locid = new WCHAR[1024];
WCHAR *locdesc = new WCHAR[1024];
//get device description information
if (!SetupDiGetDeviceInstanceId(info, &DeviceInfoData, (PTSTR)did, buffersize, &req_bufsize))
continue;
if (!SetupDiGetDeviceRegistryPropertyW(info, &DeviceInfoData, SPDRP_LOCATION_PATHS, &DataT, (LPBYTE)locid, buffersize, &req_bufsize))
continue;
if (!SetupDiGetDeviceRegistryPropertyW(info, &DeviceInfoData, SPDRP_LOCATION_INFORMATION, &DataT, (LPBYTE)locdesc, buffersize, &req_bufsize))
continue;
}
SetupDiDestroyDeviceInfoList(info);
}
上述代碼中,可以更改GUID來獲取USB設備的信息。上述代碼利用SetupDiGetDeviceInstanceID函數獲取DeviceID,通過SetupDiGetDeviceRegistryPropertyW函數來獲取相關屬性,示例中獲取了Location path和location Info,也可以獲取其他的信息,相關信息都在這裏定義。