在VS平台上用C++查找串口号,采用注册表搜索串口号的方式,本程序直接将搜索到的串口号用阿拉伯数字打印到DOS屏幕上,相关代码如下:

#include "stdafx.h"
#include<iostream>
#include<Windows.h>

using namespace std;


int GetComList_Reg()
{
	HKEY hkey;
	int result;
	int i = 0;

	result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
		_T("Hardware\\DeviceMap\\SerialComm"),
		NULL,
		KEY_READ,
		&hkey);

	if (ERROR_SUCCESS == result)   //   打开串口注册表   
	{
		TCHAR portName[0x100], commName[0x100];
		DWORD dwLong, dwSize;


		do
		{
			dwSize = sizeof(portName) / sizeof(TCHAR);
			dwLong = dwSize;
			result = RegEnumValue(hkey, i, portName, &dwLong, NULL, NULL, (LPBYTE)commName, &dwSize);
			if (ERROR_NO_MORE_ITEMS == result)
			{
				//   枚举串口
				break;   //   commName就是串口名字"COM4"
			}

			//printf("当前串口号:%c\n", commName[3]);/*输出当前串口号*/
			cout<<"当前串口号:"<< commName[3]-'0'<<endl; /*默认是字符型,需转换为阿拉伯数字*/
			i++;
		} while (1);

		RegCloseKey(hkey);
	}

	return i;
}


int main()
{
	GetComList_Reg();
	return 0;
}

//结束

运行结果如下:

C++自动查询/搜索串口号_搜索