通用串口检测模块,用Windows的API函数EnumPorts实现。
能够检测到系统中全部COM口,如COM1,COM2,...,COM256
// 枚举本机上全部COM口,结果在Ports内
procedure EnumComPorts(Ports: TStrings);
var
BytesNeeded, Returned, I: DWORD;
Success: Boolean;
PortsPtr: Pointer;
InfoPtr: PPortInfo1;
TempStr: string;
begin
Success := EnumPorts(
nil,
1,
nil,
0,
BytesNeeded,
Returned);
if (not Success) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) then
begin
GetMem(PortsPtr, BytesNeeded);
try
Success := EnumPorts(
nil,
1,
PortsPtr,
BytesNeeded,
BytesNeeded,
Returned);
for I := 0 to Returned - 1 do
begin
InfoPtr := PPortInfo1(DWORD(PortsPtr) + I * SizeOf(TPortInfo1));
TempStr := InfoPtr^.pName;
if Copy(TempStr, 1, 3) = 'COM' then
Ports.Add(Copy(TempStr, 1, Length(TempStr) - 1));
end;
finally
FreeMem(PortsPtr);
end;
end;
if not Success then
raise Exception.Create('枚举COM口失败', GetLastError);
end;