{
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
DWORD i;
//TCHAR tempDevice[MAX_PATH] = {0};
printf("Displaying the Installed Devices\n\n");
// 得到所有设备 HDEVINFO
hDevInfo = SetupDiGetClassDevs(NULL,
0, // 无类型
0, // 无回调函数
DIGCF_PRESENT | DIGCF_ALLCLASSES );
if (hDevInfo == INVALID_HANDLE_VALUE)
{
return FALSE;
}
// 循环列举
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i=0;SetupDiEnumDeviceInfo(hDevInfo,i,
&DeviceInfoData);i++)
{
DWORD DataT;
LPTSTR buffer = NULL;
DWORD buffersize = 0;
// 获取详细信息
while (!SetupDiGetDeviceRegistryProperty(
hDevInfo,
&DeviceInfoData,
SPDRP_DEVICEDESC, //SPDRP_ENUMERATOR_NAME, //SPDRP_DEVTYPE, //SPDRP_DRIVER,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
// 内存不足
if (buffer) HeapFree(GetProcessHeap(), 0, buffer);
buffer = (LPTSTR)HeapAlloc(GetProcessHeap(), 0, buffersize);
}
else
break;
}
//memcpy(tempDevice, buffer, buffersize);
string devName = GetStr(buffer);
vDeviceName.push_back(make_pair(DeviceInfoData, devName));
if (buffer) HeapFree(GetProcessHeap(), 0, buffer);
}
if ( GetLastError()!=NO_ERROR &&
GetLastError()!=ERROR_NO_MORE_ITEMS )
{
return FALSE;
}
// 释放
SetupDiDestroyDeviceInfoList(hDevInfo);
return TRUE;
}
从LPTSTR转换到string的代码如下:
string GetStr(LPTSTR value)
{
string str("");
while(*value)
{
str += *value;
value++;
}
return str;
}
打印当前电脑所有设备的GUID和名称:
vector<pair<SP_DEVINFO_DATA, string>>::iterator iter = vDeviceName.begin();
for (iter = vDeviceName.begin(); iter != vDeviceName.end(); ++iter)
{
//cout << (*iter).first << endl;
printf("GUID:{%.8X-%.4X-%.4X--%.2X%.2X-%.2X%.2X%.2X%.2X%.2X%.2X} "
"Device: %s\n", (*iter).first.ClassGuid.Data1,
(*iter).first.ClassGuid.Data2,
(*iter).first.ClassGuid.Data3,
(*iter).first.ClassGuid.Data4[0],
(*iter).first.ClassGuid.Data4[1],
(*iter).first.ClassGuid.Data4[2],
(*iter).first.ClassGuid.Data4[3],
(*iter).first.ClassGuid.Data4[4],
(*iter).first.ClassGuid.Data4[5],
(*iter).first.ClassGuid.Data4[6],
(*iter).first.ClassGuid.Data4[7],(*iter).second.c_str());
}