使用SetupApi函数通过GUID枚举系统中所有关联设备
2021-08-30
800
0
Windows的设备在驱动中大部分都会IoSetRegisterInterface,这其中一个重要的参数是GUID,这样系统会根据这个GUID给设备创建一个symbolicname,这个名字在应用层可以通过CreateFile打开。
这里分享一个在应用层通过SetuApi枚举该类型GUID下的所有设备。
BOOL USBEnumDevice(OUT PTCHAR pDeviceName, IN int instance)
{
const GUID* pGuid = &(GUID_CLASS_SELF_USB);
HDEVINFO info = SetupDiGetClassDevs((GUID*)pGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
if (info == INVALID_HANDLE_VALUE)
{
printf("No HDEVINFO available for this GUID\n");
return FALSE;
}
// Get interface data for the requested instance
SP_INTERFACE_DEVICE_DATA ifdata;
ifdata.cbSize = sizeof(ifdata);
if (!SetupDiEnumDeviceInterfaces(info, NULL, (GUID*)pGuid, instance, &ifdata))
{
//_tprintf(TEXT("No SP_INTERFACE_DEVICE_DATA available for this GUID instance\n"));
SetupDiDestroyDeviceInfoList(info);
return FALSE;
}
// Get size of symbolic link name
DWORD ReqLen;
SetupDiGetDeviceInterfaceDetail(info, &ifdata, NULL, 0, &ReqLen, NULL);
PSP_INTERFACE_DEVICE_DETAIL_DATA ifDetail = (PSP_INTERFACE_DEVICE_DETAIL_DATA)(new TCHAR[ReqLen]);
if (ifDetail == NULL)
{
SetupDiDestroyDeviceInfoList(info);
return FALSE;
}
// Get symbolic link name
ifDetail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
if (!SetupDiGetDeviceInterfaceDetail(info, &ifdata, ifDetail, ReqLen, NULL, NULL))
{
SetupDiDestroyDeviceInfoList(info);
delete ifDetail;
return FALSE;
}
//printf("Symbolic link is %s\n", ifDetail->DevicePath);
//memcpy(pDeviceName, ifDetail->DevicePath, _tcslen(ifDetail->DevicePath)*sizeof(TCHAR))//wj del
memcpy(pDeviceName, ifDetail->DevicePath, wcslen(ifDetail->DevicePath)*sizeof(TCHAR));
//pDeviceName[_tcslen(ifDetail->DevicePath)] = TEXT('\0');//wj del
pDeviceName[_tcslen(ifDetail->DevicePath)] = TEXT('\0');
delete ifDetail;
SetupDiDestroyDeviceInfoList(info);
return TRUE;
}
HID人机交互QQ群:564808376
UAC音频QQ群:218581009
UVC相机QQ群:331552032
BOT&UASP大容量存储QQ群:258159197
STC-USB单片机QQ群:315457461
USB技术交流QQ群2:580684376
USB技术交流QQ群:952873936