李sir_Blog

博客园 首页 联系 订阅 管理

读取USB设备失败可能的原因:

1.GUID不对,使用HidD_GetHidGuid获取HID的GUID。

2.参数索引没有赋值。

3.SP_INTERFACE_DEVICE_DATA变量没有初始化

4.PSP_INTERFACE_DEVICE_DETAIL_DATA 变量没有初始化。

下面是完整的打开设备代码:

 

代码
 1 BOOL OpenDevice(HANDLE& handle, WORD wVID, WORD wPID)
 2 {
 3     BOOL bRet = false;
 4     ::GUID hidGuid;
 5     ::HDEVINFO hardwareDeviceInfo;
 6     ::SP_INTERFACE_DEVICE_DATA deviceInfoData;
 7     ::PSP_INTERFACE_DEVICE_DETAIL_DATA functionClassDeviceData = NULL;
 8     ::ULONG predictedLength = 0;
 9     ::ULONG requiredLength = 0;
10 
11     handle = INVALID_HANDLE_VALUE;
12 
13     deviceInfoData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);
14     ::HidD_GetHidGuid(&hidGuid);
15     hardwareDeviceInfo = ::SetupDiGetClassDevs(&hidGuid,NULL,NULL,(DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
16 
17     if(hardwareDeviceInfo == INVALID_HANDLE_VALUE) 
18     { 
19         //Insert error handling here. 
20         return   0
21     }
22 
23     //枚举当前USB设备,与VID,PID对比找到当前设备
24     for(int i=0;i<128;i++)
25     {
26         if (!SetupDiEnumDeviceInterfaces(hardwareDeviceInfo, 0&hidGuid, i, &deviceInfoData)) 
27             continue;
28 
29         SetupDiGetDeviceInterfaceDetail(hardwareDeviceInfo, &deviceInfoData, NULL, 0&requiredLength, NULL);
30         predictedLength = requiredLength;
31         functionClassDeviceData = (PSP_INTERFACE_DEVICE_DETAIL_DATA)malloc(predictedLength);
32 
33         if (!functionClassDeviceData) 
34             continue;
35         functionClassDeviceData->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
36         if (!SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfo, &deviceInfoData, functionClassDeviceData, predictedLength, &requiredLength, NULL)) 
37             break;
38 
39         handle = CreateFile(functionClassDeviceData->DevicePath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
40 
41         if (handle != INVALID_HANDLE_VALUE)
42         {
43             HIDD_ATTRIBUTES attri;
44             HidD_GetAttributes(handle, &attri);
45             
46             if ((attri.VendorID == wVID) && (attri.ProductID == wPID))
47             {
48                 AfxMessageBox(_T("Find"));
49                 bRet = TRUE;
50                 break;
51             }
52         }
53     }
54     SetupDiDestroyDeviceInfoList(hardwareDeviceInfo);
55     return bRet;
56 }
posted on 2010-11-19 09:44  李sir  阅读(774)  评论(0编辑  收藏  举报