打开驱动设备接口代码
//打开一个设备接口
1 bool OpenDevice(GUID Guid, int maxInfNum) 2 { 3 HDEVINFO hwDevInfo = SetupDiGetClassDevs(&Guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE); 4 if ( INVALID_HANDLE_VALUE == hwDevInfo ) 5 return false; 6 for ( unsigned int infIndex = 0; infIndex < maxInfNum; ++infIndex ) 7 { 8 //Enum device interfaces 9 SP_INTERFACE_DEVICE_DATA devData; 10 11 //必须设置devData的cbSize,否则SetupDiEnumDeviceInterfaces调用会失败,GetLastError会返回1784 12 devData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA); 13 if ( SetupDiEnumDeviceInterfaces(hwDevInfo, 14 NULL, 15 &Guid, 16 infIndex, 17 &devData)) 18 { 19 DWORD symLinkLen = 0; 20 SetupDiGetDeviceInterfaceDetail(hwDevInfo, &devData, NULL, 0, &symLinkLen, NULL); 21 PSP_INTERFACE_DEVICE_DETAIL_DATA pDevDetailData = (PSP_INTERFACE_DEVICE_DETAIL_DATA)(new char[symLinkLen]); 22 23 //必须设置devData的cbSize,否则SetupDiGetDeviceInterfaceDetail调用会失败,GetLastError会返回1784 24 pDevDetailData->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA); 25 if ( !SetupDiGetDeviceInterfaceDetail(hwDevInfo, 26 &devData, 27 pDevDetailData, 28 symLinkLen, 29 &symLinkLen, 30 NULL)) 31 { 32 AfxMessageBox("SetupDiGetDeviceInterfaceDetail() FAILD!"); 33 delete pDevDetailData; 34 pDevDetailData = NULL; 35 } 36 else 37 { 38 HANDLE deviceHandle = CreateFile(pDevDetailData->DevicePath, 39 GENERIC_READ|GENERIC_WRITE, 40 0, 41 NULL, 42 OPEN_EXISTING, 43 FILE_FLAG_OVERLAPPED, 44 NULL); 45 if ( INVALID_HANDLE_VALUE != deviceHandle ) 46 { 47 AfxMessageBox("CreateFile() OK!"); 48 return true; 49 } 50 } 51 } 52 else 53 { 54 AfxMessageBox("SetupDiEnumDeviceInterfaces() FAILD!"); 55 //SetupDiDestroyDeviceInfoList(m_hwDevInfo); 56 DWORD ErrorCode = GetLastError(); 57 } 58 59 } 60 return false; 61 }
Gomen
2012.10.11