检测系统的串口(COM)个数.Thanks!(100分)

  • 主题发起人 主题发起人 licby
  • 开始时间 开始时间
L

licby

Unregistered / Unconfirmed
GUEST, unregistred user!
我想在一个下拉框中自动列出系统的所有串口。不管当前串口是否已经打开。比较简
单的方法是用Createfile,这种方法在端口没有打开时,的确是可行的,但如果串口已经
打开,则这种方法就行不通了。
我见过有人实现了的。就算是端口已经打开,一样可以检测出是否存在此端口。
请各位高手指点!谢谢了!
 
系统里面有哪些串口?
get names of available comm ports?

{
Show the names of available comm ports (com1, com2, ...)
Used registry key: hkey_local_machine/hardware/devicemap/serialcomm
}

uses
Registry;

procedure TForm1.Button1Click(Sender: TObject);
var
reg: TRegistry;
st: Tstrings;
i: Integer;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.OpenKey('hardware/devicemap/serialcomm', False);
st := TstringList.Create;
try
reg.GetValueNames(st);
for i := 0 to st.Count - 1 do
Memo1.Lines.Add(reg.Readstring(st.strings));
finally
st.Free;
end;
reg.CloseKey;
finally
reg.Free;
end;
end;


 
上面的对啊
 
其实你原来的办法也是可以的,但是注意返回数值就可以了,占用和非法端口是不同的返回数值
是 INVALID_HANDLE_VALUE和ERROR_ALREADY_EXISTS吧
var
i: Integer;
S: String;
ComName: array[0..9] of Char;
TheComHandle: Integer;

begin
PortsComboBox.Clear();
(*
** Windows 95/98 can only handle up to 50 COM ports.
** All we are doing here is checking to see if Windows
** "can" open up the COM port. If so, then we know it's
** available. And so we add it to our ComboBox list
** and of course close the COM port each time we check it.
*)
for i := 1 to 50 do
begin
StrFmt(ComName, '//./COM%d', );
TheComHandle := CreateFile
(
ComName, // name
GENERIC_READ or GENERIC_WRITE, // access attributes
0, // no sharing
nil, // no security
OPEN_EXISTING, // creation action
FILE_ATTRIBUTE_NORMAL or
FILE_FLAG_OVERLAPPED, // attributes
0 // no template
);
if (TheComHandle <> INVALID_HANDLE_VALUE) then
begin
S := Format('COM%d', );
PortsComboBox.Items.Add(S);
end;
CloseHandle(TheComHandle);
end; {end of for loop}
end;
 
对 yzhshi 的改进:
var
i: Integer;
S: String;
ComName: array[0..9] of Char;
TheComHandle: Integer;
j:Integer;
begin
PortsComboBox.Clear();
(*
** Windows 95/98 can only handle up to 50 COM ports.
** All we are doing here is checking to see if Windows
** "can" open up the COM port. If so, then we know it's
** available. And so we add it to our ComboBox list
** and of course close the COM port each time we check it.
*)
for i := 1 to 50 do
begin
StrFmt(ComName, '///COM%d', ); //原句: StrFmt(ComName, '//./COM%d', )
TheComHandle := CreateFile
(
ComName, // name
GENERIC_READ or GENERIC_WRITE, // access attributes
0, // no sharing
nil, // no security
OPEN_EXISTING, // creation action
FILE_ATTRIBUTE_NORMAL or
FILE_FLAG_OVERLAPPED, // attributes
0 // no template
);
if (TheComHandle=-1) or (TheComHandle=INVALID_HANDLE_VALUE) then
begin
j:=GetLastError;
if (j=ERROR_ACCESS_DENIED) or (j=ERROR_SUCCESS) then
begin
S := Format('COM%d', );
PortsComboBox.Items.Add(S);
end;
end
else
begin
S := Format('COM%d', );
PortsComboBox.Items.Add(S);
end;
CloseHandle(TheComHandle);
end; {end of for loop}
end;
 
谢谢各位了!
 
后退
顶部