QT 自动获取可用串口

本来想直接用Settings来获取的,但是串口信息类似 "\Device\Serial0",死活获取不了,用了转义、反斜杠还是获取不到,所以就放弃了,网上好像也没有获取成功的。
所以就用winapi来获取了,参考了网上源码

cpp文件
/*
    初始化串口
*/
void MainWindow::init_comm()
{
    QString path = "HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM";
    QSettings *settings = new QSettings(path, QSettings::NativeFormat);
    QStringList key = settings->allKeys();
    QStringList comlist ;
    QStringList Baudlist ;
//    QStringList Paritylist ;
//    QStringList DataBitslist;
//    QStringList StopBitslist;
//    QStringList ControlFlowlist;

    comlist.clear();

    /* 取串口名 */
    for (int i=0; iComPortcomboBox->addItems(comlist);

    ....
}

/*
    读取键值
*/
QString MainWindow::getcomm(int index, QString keyorvalue)
{
    QString commresult;

    if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"), 0, KEY_READ, &hKey) != 0) {
            QString error="Cannot open regedit!";//无法打开注册表时返回error
            return error;
        }//if(::RegOpenKeyEx(HKEY_LOCAL_MACHINE,subkey,0,KEY_READ,&hKey)!=0)

        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<(int)keysize; i++) {
                message = keyname[i];
                keymessage.append(message);
            }

            for (int j=0; j<(int)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;
}
 
  
 
  
.h文件

#include 
#include   
    HKEY hKey;
    LPCWSTR subkey;
    wchar_t keyname[256]; //键名数组
    char keyvalue[256];  //键值数组
    DWORD keysize,type,valuesize;
    int indexnum;


你可能感兴趣的:(QT)