/* -------- 从注册表里搜寻安装的串口 -----------------------
Win2k/XP和Win98/Me的注册表值不同,所以用枚举
把串口名字写入一个ComboBox控件里
*/
void FindCommPort( CComboBox *pComboBox )
{
HKEY hKey;
#ifdef _DEBUG
ASSERT( pComboBox != NULL );
pComboBox->AssertValid();
#endif
if( ::RegOpenKeyEx( HKEY_LOCAL_MACHINE,
"Hardware//DeviceMap//SerialComm",
NULL,
KEY_READ,
&hKey) == ERROR_SUCCESS) // 打开串口注册表
{
int i=0;
char portName[256],commName[256];
DWORD dwLong,dwSize;
while(1)
{
dwLong = dwSize = sizeof(portName);
if( ::RegEnumValue( hKey,
i,
portName,
&dwLong,
NULL,
NULL,
(PUCHAR)commName,
&dwSize ) == ERROR_NO_MORE_ITEMS ) // 枚举串口
break;
pComboBox->AddString( commName ); // commName就是串口名字
i++;
}
if( pComboBox->GetCount() == 0 )
{
::AfxMessageBox( "在HKEY_LOCAL_MACHINE:Hardware//DeviceMap//SerialComm里找不到串口!!!" );
}
RegCloseKey(hKey);
}
}
我经过简单的修改它就可以在cb 里面用了,主要还是因为这个函数用了标准的windows API.
/* -------- 从注册表里搜寻安装的串口 -----------------------
Win2k/XP和Win98/Me的注册表值不同,所以用枚举
把串口名字写入一个ComboBox控件里
*/
int FindCommPort( TComboBox *pComboBox )
{
HKEY hKey;
if(pComboBox==NULL) return 0;
if( ::RegOpenKeyEx( HKEY_LOCAL_MACHINE,
"Hardware//DeviceMap//SerialComm",
NULL,
KEY_READ,
&hKey) == ERROR_SUCCESS) // 打开串口注册表
{
int i=0;
char portName[256],commName[256];
DWORD dwLong,dwSize;
while(1)
{
dwLong = dwSize = sizeof(portName);
if( ::RegEnumValue( hKey,
i,
portName,
&dwLong,
NULL,
NULL,
(PUCHAR)commName,
&dwSize ) == ERROR_NO_MORE_ITEMS ) // 枚举串口
break;
pComboBox->Items->Add(commName ); // commName就是串口名字
i++;
}
RegCloseKey(hKey);
if( pComboBox->Items->Count == 0 )
{
ShowMessage( "在HKEY_LOCAL_MACHINE:Hardware//DeviceMap//SerialComm里找不到串口!!!" );
return 0;
}
return 1;
}
}
//delphi的版本
Procedure GetPortList(slPort:TStringList);
var
reg : TRegistry;
ts : TStrings;
i : integer;
sName,sPort:string;
slList:TStringList;
begin
reg := TRegistry.Create;
ts := TStringList.Create;
slList:=TStringList.Create;
try
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.OpenKey('hardware/devicemap/serialcomm',false);
reg.GetValueNames(ts);
slList.Sorted:=true;
for i := 0 to ts.Count -1 do begin
sName:=LowerCase(Trim(ts.Strings[i]));
//得到串口名称
sPort := UpperCase(Trim(reg.ReadString(sName)));
if Copy(sPort,1,3) <> 'COM' then Continue;
sPort:=Copy(sPort,4,Length(sPort));
sPort:=FormatFloat('000',StrToInt(sPort));
slList.Add(sPort);
end;
slPort.Clear;
for i:=0 to slList.Count-1 do
slPort.Add('COM'+IntToStr(StrToInt(slList.Strings[i])));
finally
ts.Free;
reg.CloseKey;
reg.free;
end;
end;