一般來說,PC機上都有串口。如何獲取這些串口的數目以及串口的編號呢?我以前就遇到過這樣的問題。當時是編了一個小模塊,專門用來查看機器上的串口。首先假設機器上有某個串口(例如COM1),然後嘗試著的打開。如果失敗,則說明假設是失敗的,即這個串口不存在。否則這個串口存在。就這樣一個個的試。是不是有點像數學裡的反證法?!現在想起來這是多麼笨的方法呀!
串口是一種系統資源。由操作系統統一管理。可想而知,系統注冊表(Windows,其他系統大同小異)裡肯定有相應的記錄。的確如此。下面就給出根據這個思想寫的程序:
DWord GetAllPorts(CComboBox * pComBox)
...{
CString strPath;
strPath = _T("HARDWARE\DEVICEMAP\SERIALCOMM");
HKEY hKey;
// The RegOpenKeyEx function opens the specifIEd registry key.
// Note that the key names is not case sensitive.
if(RegOpenKeyEx(HKEY_LOCAL_MacHINE, strPath, 0, KEY_ALL_Access, &hKey) != ERROR_SUCCESS)
...{
RegCloseKey(hKey);
return 0;
}
TCHAR achClass[MAX_PATH] = _T(""); // buffer for class name
DWord cchClassName = MAX_PATH; // size of class string
DWord cSubKeys; // number of subkeys
DWord cbMaxSubKey; // longest subkey size
DWord cchMaxClass; // longest class string
DWord cValues; // number of values for key
DWord cchMa
xValue; // longest value name
DWord cbMaxValueData; // longest value data
DWord cbSecurityDescriptor; // size of security descriptor
FILETIME ftLastWriteTime; // last write time
TCHAR achValue[MAX_PATH];
DWord cchValue = MAX_PATH;
BYTE achBuff[80];
DWord chValue = 60;
DWord type = REG_SZ;
// Get the class name and the value count.
if(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)!=ERROR_SUCCESS) // last write time
...{
RegCloseKey( hKey );
return 0;
}
CString sList;
if (cValues)
...{
for (DWord j = 0, retValue = ERROR_SUCCESS; j < cValues; j++)
...{
chValue = 60;
cchValue = 60;
retValue = RegEnumValue(hKey, j, achValue,
&cchValue,
NULL,
&type, // &dwType,
achBuff, // &bData,
&chValue); // &bcData
if(retValue == ERROR_SUCCESS)
...{
sList += (LPTSTR)(achBuff);
pComBox->AddString(LPTSTR(achBuff));
}
}
}
RegCloseKey( hKey );
return cValues;
}