1. 程式人生 > >Windows下USB磁碟開發系列二:列舉系統中所有USB裝置

Windows下USB磁碟開發系列二:列舉系統中所有USB裝置

上篇 《Windows下USB磁碟開發系列一:列舉系統中U盤的碟符》介紹了很簡單的獲取系統U盤碟符的辦法,現在介紹下如何列舉系統中所有USB裝置(不光是U盤)。

主要呼叫的API如下:

1,呼叫SetupDiGetClassDevs()獲取指定裝置型別的控制代碼;

2,呼叫SetupDiEnumDeviceInfo()列舉裝置資訊;

3,呼叫SetupDiGetDeviceRegistryProperty()獲取裝置資訊。

 

具體實現函式如下:

int enum_usb_device_info()
{		
	int i = 0;
	int res = 0;
	HDEVINFO hDevInfo;  
	SP_DEVINFO_DATA DeviceInfoData = {sizeof(DeviceInfoData)};   
 
	// get device class information handle
	hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_USB,0, 0, DIGCF_PRESENT);       
	if (hDevInfo == INVALID_HANDLE_VALUE)     
	{         
		res = GetLastError();     
		return res;
	}  
 
	// enumerute device information
	DWORD required_size = 0;
	for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
	{		
		DWORD DataT;         
		char friendly_name[2046] = {0};         
		DWORD buffersize = 2046;        
		DWORD req_bufsize = 0;      
		
		// get device description information
		if (!SetupDiGetDeviceRegistryPropertyA(hDevInfo, &DeviceInfoData, SPDRP_DEVICEDESC, &DataT, (LPBYTE)friendly_name, buffersize, &req_bufsize))
		{
			res = GetLastError();
			continue;
		}
		
		char temp[512] = {0};
		sprintf_s(temp, 512, "USB device %d: %s", i, friendly_name);
		puts(temp);
	}
 
	return 0;
}

 

注意:如果使用SetupDiGetDeviceRegistryProperty()試圖獲取SPDRP_FRIENDLYNAME屬性時,有些裝置回返回ERROR_INVALID_DATA(13)的錯誤,因為可能Friendly Name不存在,所以本例中採用獲取SPDRP_DEVICEDESC屬性的方法。

 

呼叫上面函式的輸出結果如下: