在编写串口代码时,需要枚举当前系统上的串口,通过api RegEnumValueA(W)可以遍历注册表HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM下的项,枚举串口,代码如下:
#include <Windows.h>
#pragma comment(lib, "Advapi32.lib")
void EnumSerialCom()
{
HKEY hKey;
TCHAR *pSubKey = L"Hardware\\DeviceMap\\SerialComm";
int ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, pSubKey, 0, KEY_READ, &hKey);
if (ret != ERROR_SUCCESS)
{
printf("打开注册表失败\n");
return;
}
TCHAR szPortName[256] = { 0 }, szComName[256] = { 0 };
DWORD dwLong, dwSize;
int nCount = 0;
while (true)
{
dwLong = dwSize = 256;
LSTATUS lstatus = RegEnumValue(hKey, nCount, szPortName, &dwLong, NULL, NULL, (PUCHAR)szComName, &dwSize);
if (ERROR_MORE_DATA == lstatus)
{
printf("缓冲区太小\n");
break;
}
if (ERROR_SUCCESS != lstatus)
{
if (lstatus == ERROR_NO_MORE_ITEMS)//表示枚举完毕
break;
}
printf("%ls %ls\n", szPortName, szComName);
nCount++;
}
RegCloseKey(hKey);
}