使用SetupApi函数通过GUID枚举系统中所有关联设备

8 0 2021-06-29 本文地址:http://www.usbzh.com/fun/detail-34.html

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;
}
取消
感谢您的支持,我会继续努力的!
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

您的支持,是我们前进的动力!