多數(shù)涉及串口操作的軟件,在讓用戶選擇串口時(shí),只會(huì)機(jī)械的給出從COM1到COM16的組合框。但實(shí)際上可能有大于COM16的串口號(hào),于是想編程來獲取實(shí)際的串口號(hào)再列出來??雌饋砗茈y,其實(shí)關(guān)于串口的信息保存了注冊(cè)表中,代碼如下: void CPageSetCom::ShowComm() { long lReg; HKEY hKey; DWORD MaxValueLength; DWORD dwValueNumber; lReg=RegOpenKeyExA(HKEY_LOCAL_MACHINE, 'HARDWARE\\DEVICEMAP\\SERIALCOMM', 0, KEY_QUERY_VALUE, &hKey); if(lReg!=ERROR_SUCCESS) { AfxMessageBox(L'Open Registry Error!\n'); return; } lReg=RegQueryInfoKeyA(hKey, NULL, NULL, NULL, NULL, NULL, NULL, &dwValueNumber, //返回和hKey關(guān)聯(lián)的值 &MaxValueLength, NULL, NULL, NULL); if(lReg!=ERROR_SUCCESS) //沒有成功 { AfxMessageBox(L'Getting Info Error!\n'); return; } LPSTR pValueName,pCOMNumber; DWORD cchValueName,dwValueSize=6; for(DWORD i=0;i < dwValueNumber;i++) { cchValueName=MaxValueLength+1; dwValueSize=6; pValueName=(LPSTR)VirtualAlloc(NULL,cchValueName,MEM_COMMIT,PAGE_READWRITE); lReg=RegEnumValueA(hKey, i, pValueName, &cchValueName, NULL, NULL, NULL, NULL); if((lReg!=ERROR_SUCCESS)&&(lReg!=ERROR_NO_MORE_ITEMS)) { AfxMessageBox(L'Enum Registry Error or No More Items!\n'); continue; } pCOMNumber=(LPSTR)VirtualAlloc(NULL,6,MEM_COMMIT,PAGE_READWRITE); lReg=RegQueryValueExA(hKey, pValueName, NULL, NULL, (LPBYTE)pCOMNumber, &dwValueSize); if(lReg!=ERROR_SUCCESS) { AfxMessageBox(L'Can not get the name of the port'); continue; } CString strCommList; //AfxMessageBox(pCOMNumber); CharToUnicode(pCOMNumber,&strCommList); //m_ctlPort.AddString(strCommList); BOOL m_bInsert=0; if(((CComboBox*)GetDlgItem(IDC_CMBREADERCOM))->GetCount()==0) ((CComboBox*)GetDlgItem(IDC_CMBREADERCOM))->AddString(strCommList); else { CString strTemp=strCommList; strCommList.TrimLeft(L'COM'); for(int icurrent=0;icurrent<((CComboBox*)GetDlgItem(IDC_CMBREADERCOM))->GetCount();icurrent++) { CString strCurrent; ((CComboBox*)GetDlgItem(IDC_CMBREADERCOM))->GetLBText(icurrent,strCurrent); strCurrent.TrimLeft(L'COM'); if(_ttol(strCurrent)>_ttol(strCommList)) { ((CComboBox*)GetDlgItem(IDC_CMBREADERCOM))->InsertString(icurrent,strTemp); m_bInsert = 1; break; } } if(!m_bInsert) ((CComboBox*)GetDlgItem(IDC_CMBREADERCOM))->InsertString(icurrent,strTemp); } VirtualFree(pValueName,0,MEM_RELEASE); VirtualFree(pCOMNumber,0,MEM_RELEASE); } } int CPageSetCom::CharToUnicode(char *pchIn, CString *pstrOut) { int nLen; WCHAR *ptch; if(pchIn == NULL) { return 0; } nLen = MultiByteToWideChar(CP_ACP, 0, pchIn, -1, NULL, 0); ptch = new WCHAR[nLen]; MultiByteToWideChar(CP_ACP, 0, pchIn, -1, ptch, nLen); pstrOut->Format(_T('%s'), ptch); delete [] ptch; return nLen; } |
|