在做设备串口通讯时,往往需要自动连接到想要连接的usb转串口设备上。
#include <Setupapi.h> int CMFCApplication1Dlg::FindUSBCOM() { #pragma comment(lib, "setupapi.lib") HDEVINFO hDevInfo = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT); if (hDevInfo == INVALID_HANDLE_VALUE) { AfxMessageBox(_T("获取系统设备列表失败")); return -1; } SP_DEVINFO_DATA deviceInfoData; deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); deviceInfoData.DevInst = 0; deviceInfoData.Reserved = 0; DWORD regDataType; LPTSTR buffer = new TCHAR[200]; DWORD buffersize = 200; LPTSTR bufferVid = new TCHAR[200]; DWORD buffersizeVid = 200; LPTSTR bufferPortNum = new TCHAR[200]; DWORD buffersizePortNum = 200; int portNum = 0;//Com1 portNum=1 for (int i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &deviceInfoData); i++) { buffersize = 200; SetupDiGetDeviceRegistryProperty(hDevInfo, &deviceInfoData, SPDRP_CLASS, ®DataType, (PBYTE)buffer, buffersize, &buffersize); if (CString(buffer).MakeUpper() == "PORTS") { buffersizePortNum = 200; SetupDiGetDeviceRegistryProperty(hDevInfo, &deviceInfoData, SPDRP_FRIENDLYNAME, ®DataType, (PBYTE)bufferPortNum, buffersizePortNum, &buffersizePortNum); int comIndex = CString(bufferPortNum).MakeUpper().Find(_T("COM")); if (comIndex > -1) { //Silicon Labs CP210x USB to UART Bridge (COM4) portNum = _ttoi(CString(bufferPortNum).Mid(comIndex + 3, 1)); } buffersizeVid = 200; SetupDiGetDeviceRegistryProperty(hDevInfo, &deviceInfoData, SPDRP_HARDWAREID, ®DataType, (PBYTE)bufferVid, buffersizeVid, &buffersizeVid); if (CString(bufferVid).MakeUpper().Find(_T("VID_10C4")) > -1) { if (buffer != nullptr) { delete[] buffer; } if (bufferVid != nullptr) { delete[] bufferVid; } if (bufferPortNum != nullptr) { delete[] bufferPortNum; } // 释放设备 SetupDiDestroyDeviceInfoList(hDevInfo); return portNum; } }//end if ports }// end for if (buffer != nullptr) { delete[] buffer; } if (bufferVid != nullptr) { delete[] bufferVid; } if (bufferPortNum != nullptr) { delete[] bufferPortNum; } // 释放设备 SetupDiDestroyDeviceInfoList(hDevInfo); return portNum; }