进行串口通信之前,需要获取当前系统的可用串口。要想达到此目的,有两种方式,读取注册表和使用CreateFile函数轮询读取串口。
1.使用CreateFile轮询读取串口:
1 UINT CComDebugToolDlg::GetSerialPortState() 2 { 3 CString strCom; 4 int nCom=0; 5 HANDLE hCom; 6 7 do 8 { 9 nCom++; 10 strCom.Format("COM%d",nCom); 11 12 hCom=CreateFile(strCom,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,0);//轮询打开串口 13 if (INVALID_HANDLE_VALUE==hCom) 14 { 15 DWORD err=::GetLastError(); 16 } 17 else 18 { 19 m_comCbx.AddString(strCom); 20 } 21 CloseHandle(hCom);//关闭串口 22 } while (nCom<256); 23 m_comCbx.SetCurSel(0); 24 return 0; 25 }
2.读取注册表
1 UINT CComDebugToolDlg::GetSerialPortState() 2 { 3 LPCTSTR strReg="HARDWARE\\DEVICEMAP\\SERIALCOMM"; 4 HKEY hKey; 5 CString strSerialPortList[256]; 6 int i=0; 7 8 long ret=0; 9 DWORD dwIndex=0; 10 char name[25]={0}; 11 DWORD dwName; 12 DWORD dwType; 13 UCHAR szPortName[25]={0}; 14 DWORD szPortNameOfBytes=sizeof(szPortName); 15 16 ret=::RegOpenKeyEx(HKEY_LOCAL_MACHINE,strReg,0,KEY_READ,&hKey); 17 if (ret!=ERROR_SUCCESS) 18 { 19 return -1; 20 } 21 22 do 23 { 24 ret=RegEnumValue(hKey,dwIndex++,name,&dwName,NULL,&dwType,szPortName,&szPortNameOfBytes); 25 if (ret==ERROR_SUCCESS||ret==ERROR_MORE_DATA) 26 { 27 strSerialPortList[i]=(CString)szPortName; 28 m_comCbx.AddString(strSerialPortList[i]); 29 i++; 30 } 31 32 } while (ret=ERROR_SUCCESS||ret==ERROR_MORE_DATA); 33 RegCloseKey(hKey); 34 35 m_comCbx.SetCurSel(0); 36 37 return 0; 38 }
时间: 2024-09-29 17:15:17