简体   繁体   中英

How to filter Windows api device Info from only connected devices?

I am working on a application to find all USB devices with a COM port. My current method finds a list of all com devices however, this list includes device that are not currently connected. How can I filter out unconnected devices?

I am trying to avoid trying to establish a connection to the device because the list can be very large.

void FindDevice() {
    SP_DEVINFO_DATA spDevInfoData;
    QString szClass("USB");
    HDEVINFO hDevInfo = GetHDevInfo(szClass);
    spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    for(int i=0; SetupDiEnumDeviceInfo(hDevInfo, i, &spDevInfoData); i++) {
        DWORD nSize=0 ;
        TCHAR buf[MAX_PATH];
        if ( !SetupDiGetDeviceInstanceId(hDevInfo, &spDevInfoData, buf, sizeof(buf), &nSize) ) {
            continue;
        }
        QString value(QString::fromWCharArray(buf));
        addDevice(value);
    }
    update();
}

Instead of using GetHDevInfo you should use SetupDiGetClassDevsEx to get the HDEVINFO object. You can pass that function a flag named DIGCF_PRESENT which ensures that only connected devices are returned.

Without having tested it for now, this should work:

HDEVINFO hDevInfo = SetupDiGetClassDevsEx(GUID_DEVINTERFACE_USB_DEVICE,
                                          nullptr,
                                          nullptr,
                                          DIGCF_ALLCLASSES | DIGCF_PRESENT,
                                          nullptr,
                                          nullptr,
                                          nullptr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM