得到可用端口列表:
procedure EnumPorts( PortList: TStrings );
var
MaxPorts : integer;
hPort : THandle;
PortNumber : integer;
PortName : string;
begin
if PortList = nil then EXIT;
{ where are we running on? }
case Win32PlatForm of
VER_PLATFORM_WIN32_NT: MaxPorts := 256;
VER_PLATFORM_WIN32_WINDOWS: MaxPorts := 9;
end;
for PortNumber := 1 to MaxPorts do
begin
if PortNumber > 9 then
PortName := '//./COM' + IntToStr( PortNumber ) // ask Microsoft why...
else
PortName := 'COM' + IntToStr( PortNumber );
hPort := CreateFile( PChar( PortName ),
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
0,
0 );
// 注意:如果端口已经被其它程序占用,这里不再列出
if not ( hPort = INVALID_HANDLE_VALUE ) then
PortList.Add( PortName );
CloseHandle( hPort );
end;
end;