一、Windows下开发,怎么获取当前串口呢
- 使用Qt的童鞋都知道,Qt提供了丰富的接口,包括串口。但是对于串口的支持,是从Qt5开始的,对于Qt4来说,虽然也可以使用Qt的库,但是并不是很方便。不是Qt环境就更不用说了。本文提供了一个封装好的方法,可以方便的获取当前可用的串口。
二、代码实现
#include "string.h"
#include "stdio.h"
#include <vector>
#include <string>
#include <atlbase.h>
char* wideCharToMultiByte(wchar_t* pWCStrKey)
{
int pSize = WideCharToMultiByte(CP_OEMCP, 0, pWCStrKey, wcslen(pWCStrKey), NULL, 0, NULL, NULL);
char* pCStrKey = new char[pSize + 1];
WideCharToMultiByte(CP_OEMCP, 0, pWCStrKey, wcslen(pWCStrKey), pCStrKey, pSize, NULL, NULL);
pCStrKey[pSize] = '\0';
return pCStrKey;
}
std::vector<std::string> getComPort()
{
HKEY hKey;
wchar_t portName[256], w_commName[256];
std::vector<std::string> comName;
if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Hardware\\DeviceMap\\SerialComm"), NULL, KEY_READ, &hKey))
{
int i = 0;
int mm = 0;
DWORD dwLong, dwSize;
while (TRUE)
{
dwLong = dwSize = sizeof(portName);
if (ERROR_NO_MORE_ITEMS == ::RegEnumValue(hKey, i, portName, &dwLong, NULL, NULL, (PUCHAR)w_commName, &dwSize))
{
break;
}
char* commName = wideCharToMultiByte(w_commName);
comName.push_back(commName);
delete[] commName;
i++;
}
RegCloseKey(hKey);
}
return comName;
}
QString getAvailableSerialPortTest()
{
std::vector<int> vecPortList;
std::vector<std::string> vecList = getComPort();
for (int i = 0;i<vecList.size();i++)
{
std::string strCom = vecList[i];
std::string strPort = strCom.substr(3,1);
int nPort = stoi(strPort,0,10);
vecPortList.push_back(nPort);
}
QString strExist;
for (int i=0;i<vecPortList.size();i++)
{
strExist+=QString::number(vecPortList[i]) + " ";
}
return strExist;
}
三、总结
- 以上程序,可以快速方便的获取可用端口。但是,只限于windows系统。