Windows下USB磁盘开发系列二:枚举系统中所有USB设备

现在介绍下如何枚举系统中所有USB设备(不光是U盘)。主要调用的API如下:

1,调用SetupDiGetClassDevs()获取指定设备类型的句柄;

2,调用SetupDiEnumDeviceInfo()枚举设备信息;

3,调用SetupDiGetDeviceRegistryProperty()获取设备信息。

具体实现函数如下:

int enum_usb_device_info()
{        
    int i = 0;
    int res = 0;
    HDEVINFO hDevInfo;  
    SP_DEVINFO_DATA DeviceInfoData = {sizeof(DeviceInfoData)};   

    // get device class information handle
    hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_USB,0, 0, DIGCF_PRESENT);       
    if (hDevInfo == INVALID_HANDLE_VALUE)     
    {         
        res = GetLastError();     
        return res;
    }  

    // enumerute device information
    DWORD required_size = 0;
    for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
    {        
        DWORD DataT;         
        char friendly_name[2046] = {0};         
        DWORD buffersize = 2046;        
        DWORD req_bufsize = 0;      
        
        // get device description information
        if (!SetupDiGetDeviceRegistryPropertyA(hDevInfo, &DeviceInfoData, SPDRP_DEVICEDESC, &DataT, (LPBYTE)friendly_name, buffersize, &req_bufsize))
        {
            res = GetLastError();
            continue;
        }
        
        char temp[512] = {0};
        sprintf_s(temp, 512, "USB device %d: %s", i, friendly_name);
        puts(temp);
    }

    return 0;
}

注意:如果使用SetupDiGetDeviceRegistryProperty()试图获取SPDRP_FRIENDLYNAME属性时,有些设备回返回ERROR_INVALID_DATA(13)的错误,因为可能Friendly Name不存在,所以本例中采用获取SPDRP_DEVICEDESC属性的方法。

调用上面函数的输出结果如下:

posted @ 2014-10-13 19:05  Max Woods  阅读(1871)  评论(0编辑  收藏  举报