0

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();
}
4

1 回答 1

1

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);
于 2013-10-04T14:06:49.427 回答