打开注册表
菜单-》运行
输入regedit
到目录
HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM\\
中,该目录下有的com口表示系统当前存在的com
//获取系统串口注册表中index索引位置的键名或键值 //QString为value字符串时为获取键值,键值即com名 QString getcomm(int index, QString keyorvalue) { QString commresult = ""; QString strkey = "HARDWARE\\DEVICEMAP\\SERIALCOMM";//子键路径 int a = strkey.toWCharArray(subkey); subkey[a] = L'\0'; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, subkey, 0, KEY_READ|KEY_QUERY_VALUE, &hKey) != 0 ) { QMessageBox::question(NULL, QString("错误"), QString("注册表打开失败\r\n请检查注册表路径是否正确!")); } QString keymessage = "";//键名 QString message = ""; QString valuemessage = "";//键值 indexnum = index;//要读取键值的索引号 keysize = sizeof(keyname); valuesize = sizeof(keyvalue); if ( ::RegEnumValue(hKey, indexnum, keyname, &keysize, 0, &type, (BYTE*)keyvalue, &valuesize) == 0 ) { //读取键名 //for (int i = 0; i <keysize; i++) { message = QString::fromStdWString(keyname); keymessage.append(message); } //读取键值 for (int j = 0; j < valuesize; j++) { if (keyvalue[j] != 0x00 ) { valuemessage.append(keyvalue[j]); } } if ( keyorvalue == "key" ) { commresult = keymessage; } if ( keyorvalue == "value" ) { commresult = valuemessage; } } else { commresult = "nokey"; } ::RegCloseKey(hKey); //关闭注册表 return commresult; } //系统存在串口以及其他所有串口放入到comboxcomlist列表中 void init_comlist(void) { QString path = "HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM"; QSettings *settings = new QSettings(path, QSettings::NativeFormat); QStringList key = settings->allKeys(); //系统注册表中com存在的个数 int comkeycount = key.size(); //qDebug() << comkeycount << key; //2 ("/Device/Serial0", "/Device/VCP0") regcomlist.clear(); comboxcomlist.clear(); for ( int i = 0; i < comkeycount; i++ ) { //将注册表中有的com名字放入列表中 //qDebug() << getcomm(i, "key"); regcomlist << getcomm(i, "value"); //qDebug() << regcomlist.value(i); } qDebug() << regcomlist; qDebug() << create_user_virtual_comlist; qDebug() << create_private_virtual_comlist; //两种情况,第一种,系统注册表此时有虚拟串口的信息,那么要将保存系统注册表中串口信息的regcomlist列表中删除掉虚拟串口,create_user_virtual_comlist,create_private_virtual_comlist已经保存了上次的虚拟串口列表 //for ( int i = 0; create_user_virtual_comlist; ) //第二种,系统注册表此时没有虚拟串口信息,只有本机串口信息,那么就不需要删除 bool findflag = false; for ( int i = 0; i < MOST_VIRTUAL_COM_NUM; i++ )//combox组件中添加255个com { findflag = false; //遍历保存注册表中com的列表 for ( int j = 0 ; j < comkeycount; j++ ) { if ( QString::compare(regcomlist.value(j), QString("COM%1").arg(i + 1)) == 0 ) { comboxcomlist << QString(regcomlist.value(j) + QString(" (本机)")); findflag = true; break; } } if ( findflag == true ) continue; comboxcomlist << QString("COM%1").arg(i + 1); }