QT 自動獲取可用串列埠
阿新 • • 發佈:2019-01-04
本來想直接用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; i<key.size(); i++) { comlist << getcomm(i, "value"); } ui->ComPortcomboBox->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 <QSettings>
#include <qt_windows.h>
HKEY hKey;
LPCWSTR subkey;
wchar_t keyname[256]; //鍵名陣列
char keyvalue[256]; //鍵值陣列
DWORD keysize,type,valuesize;
int indexnum;