본문 바로가기

Software/Network

[REGISTRY] Query available COM Port Logic

아래 있는 GetComPortList함수를 이용하면 현재 시스템에 인스톨된 COM포트 목록을 구할 수 있습니다.

디폴트 파라매터로 된 OnlyAvail를 True로 넣어주시면 사용 가능한 포트만 검색 할 수도 있습니다.

uses절에 Registry와 Windows, Classes유닛을 추가해서 사용하세요...

사용법:

    GetComPortList(Listbox1.Items);
    GetComPortList(Listbox1.Items, True);

function ValidateComPort(ComPort : PChar): Boolean;
// COM포트가 사용가능한지 알아낸다.
var
    PortHandle: THandle;
begin
    Result := False;
    PortHandle := CreateFile(ComPort, GENERIC_READ or GENERIC_WRITE, 0, nil,
        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
    if (PortHandle <> INVALID_HANDLE_VALUE) then
    begin
        Result := True;
        CloseHandle(PortHandle);
    end;
end;

procedure GetComPortList(List: TStrings; OnlyAvail: Boolean = False);
// 현재 인스톨된 COM포트 목록을 구한다.
var
    RegFile: TRegistry;
    DeviceList: TStrings;
    DeviceCount: Integer;
    CanAddPort: Boolean;
    CurrentPort: string;
begin
    if Assigned(List) then
    begin
        RegFile := TRegistry.Create;
        try
            RegFile.RootKey := HKEY_LOCAL_MACHINE;
            RegFile.OpenKeyReadOnly('hardware\devicemap\serialcomm');
            DeviceList := TStringList.Create;
            try
                RegFile.GetValueNames(DeviceList);
                List.Clear;
                for DeviceCount := 0 to DeviceList.Count - 1 do
                begin
                    CurrentPort := RegFile.ReadString(DeviceList.Strings[DeviceCount]);
                    if OnlyAvail then
                        CanAddPort := ValidateComPort(PChar(CurrentPort))
                    else
                        CanAddPort := True;
                    if CanAddPort then
                        List.Add(CurrentPort);
                end;
            finally
                DeviceList.Free;
            end;
            RegFile.CloseKey;
        finally
            RegFile.Free;
        end;
    end;
end;