本文主要是介绍MFC下边自动寻找串口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
摘自:http://blog.csdn.net/itas109/article/details/18359295
程序:http://blog.csdn.net/itas109/article/details/18359295
serial类里边的两个函数
void CSerialPort::Hkey2ComboBox(CComboBox& m_PortNO)
{HKEY hTestKey;bool Flag = FALSE;///仅是XP系统的注册表位置,其他系统根据实际情况做修改if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"), 0, KEY_READ, &hTestKey) ){QueryKey(hTestKey);}RegCloseKey(hTestKey);int i = 0;m_PortNO.ResetContent();///刷新时,清空下拉列表内容while(i < MaxSerialPortNum && -1 != m_nComArray[i]){CString szCom; szCom.Format(_T("COM%d"), m_nComArray[i]);m_PortNO.InsertString(i, szCom.GetBuffer(5));++i;Flag = TRUE;if (Flag)///把第一个发现的串口设为下拉列表的默认值m_PortNO.SetCurSel(0);}}
///查询注册表的串口号,将值存于数组中
///本代码参考于mingojiang的获取串口逻辑名代码
//
void CSerialPort::QueryKey(HKEY hKey)
{ #define MAX_KEY_LENGTH 255#define MAX_VALUE_NAME 16383// TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name// DWORD cbName; // size of name string TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name DWORD cchClassName = MAX_PATH; // size of class string DWORD cSubKeys=0; // number of subkeys DWORD cbMaxSubKey; // longest subkey size DWORD cchMaxClass; // longest class string DWORD cValues; // number of values for key DWORD cchMaxValue; // longest value name DWORD cbMaxValueData; // longest value data DWORD cbSecurityDescriptor; // size of security descriptor FILETIME ftLastWriteTime; // last write time DWORD i, retCode; TCHAR achValue[MAX_VALUE_NAME]; DWORD cchValue = MAX_VALUE_NAME; // Get the class name and the value count. retCode = RegQueryInfoKey(hKey, // key handle achClass, // buffer for class name &cchClassName, // size of class string NULL, // reserved &cSubKeys, // number of subkeys &cbMaxSubKey, // longest subkey size &cchMaxClass, // longest class string &cValues, // number of values for this key &cchMaxValue, // longest value name &cbMaxValueData, // longest value data &cbSecurityDescriptor, // security descriptor &ftLastWriteTime); // last write time for (i=0;i<20;i++)///存放串口号的数组初始化{m_nComArray[i] = -1;}// Enumerate the key values. if (cValues > 0) {for (i=0, retCode=ERROR_SUCCESS; i<cValues; i++) { cchValue = MAX_VALUE_NAME; achValue[0] = '\0'; if (ERROR_SUCCESS == RegEnumValue(hKey, i, achValue, &cchValue, NULL, NULL, NULL, NULL)) { CString szName(achValue);
// if (-1 != szName.Find(_T("Serial")) || -1 != szName.Find(_T("VCom")) ){if (-1 != szName.Find(_T("Serial")) || -1 != szName.Find(_T("VCom")) || -1 != szName.Find(_T("Silabser"))){BYTE strDSName[10]; memset(strDSName, 0, 10);DWORD nValueType = 0, nBuffLen = 10;if (ERROR_SUCCESS == RegQueryValueEx(hKey, (LPCTSTR)achValue, NULL, &nValueType, strDSName, &nBuffLen)){int nIndex = -1;while(++nIndex < MaxSerialPortNum){if (-1 == m_nComArray[nIndex]) {m_nComArray[nIndex] = atoi((char*)(strDSName + 3));break;}}}}} }}else{AfxMessageBox(_T("本机没有串口....."));}}
这篇关于MFC下边自动寻找串口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!