unit Unit3;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls, Registry;

type
  TForm3 = class(TForm)
    Panel1: TPanel;
    ComboBox1: TComboBox;
    ComboBox2: TComboBox;
    Button1: TButton;
    Button2: TButton;
    procedure FormShow(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form3: TForm3;

function GetPortString(var CommString:string):boolean;

implementation

{$R *.DFM}


function FindPorts:string;               // search registry for serial ports
var List:TStringList;
     Reg:TRegistry;
       I:integer;

begin
  Reg:=TRegistry.Create;
  List:=TStringList.Create;

  with Reg do
  try
    RootKey:=HKEY_LOCAL_MACHINE;
    if OpenKeyReadOnly('hardware\devicemap\serialcomm') then
    begin
      GetValueNames(List);
      for I:=0 to List.Count-1 do
        List.Strings[I]:=ReadString(List.Strings[I])
    end;
  finally
    CloseKey
  end;
  Reg.Free;
  List.Sort;
  result:=List.Text;
  List.Free
end;


function GetPortString(var CommString:string):boolean;
var S1,S2:string;
        I:integer;
begin
  result:=false;
  I:=pos(':',CommString);
  if I=0 then begin
                S1:=CommString;                                // contains only a port name
                S2:='38400'                                    // use default baud rate: 38400
              end
         else begin
                S1:=copy(CommString,1,I-1);                    // port name
                S2:=copy(CommString,I+1,length(CommString)-I); // baud rate
                try StrToInt(S2) except S2:='38400' end;       // invalid rate -> use default
              end;

  with Form3 do
  begin
    ComboBox1.Items.Text:=FindPorts;                           // get list of valid ports
    if ComboBox1.Items.Count=0 then ShowMessage('No Serial Ports Found') else
    begin
      ComboBox1.ItemIndex:=0;                                  // select first in list
      ComboBox2.ItemIndex:=9;                                  // select 38400 in list

//    if ComboBox1.Items.Count<>0 then
      for I:=ComboBox1.Items.Count-1 downto 0 do
        if ComboBox1.Items[I]=S1 then ComboBox1.ItemIndex:=I;  // find port match

//    if ComboBox2.Items.Count<>0 then
      for I:=ComboBox2.Items.Count-1 downto 0 do
        if ComboBox2.Items[I]=S2 then ComboBox2.ItemIndex:=I;  // find baud match

      I:=ShowModal;                                            // pops up form
      if I=mrOk then CommString:=ComboBox1.Text+':'+ComboBox2.Text;
      result:=(I=mrOk)
    end
  end
end;


procedure TForm3.FormShow(Sender: TObject);
begin
  Button1.SetFocus
end;


end.
