Train_RFID/util/comPort/ComPortTool.cpp

52 lines
1.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// Created by Mr.V on 2024/1/20.
//
#include "ComPortTool.h"
// 字符串转换
char* ComPortTool::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;
//如果想要转换成string直接赋值即可
//string pKey = pCStrKey;
}
std::vector<std::string> ComPortTool::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;
}