Code snippet for Lazarus to add detected serial ports to a Combo Box (on Windows)

{The following code adds the serial ports detected by Microsoft Windows into a Combo Box. Unfortunately, if a serial port is added after the application is started, it won’t be added in the combo box.}

procedure TSerial.ComboBoxAddPorts(combo_box: TComboBox);
var
i,nb_ports: integer;
my_dwSize: DWORD;
cc: TCommConfig;
Port_Name: ansistring;

begin
nb_ports := 0;
my_dwSize := SizeOf(cc);

{ I included a modified code snippet; here’s the copyright of the original code below.
The original code had up to 9 methods of getting the available serial ports. Here,
I selected one of the simplest that could be translated in pascal.

Copyright (c) 1998 – 2009 by PJ Naughter (Web: http://www.naughter.com, Email: pjna@naughter.com)

All rights reserved.

Copyright / Usage Details:

You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
when your product is released in binary form. You are allowed to modify the source code in any way you want
except you cannot modify the copyright details at the top of each module. If you want to distribute source
code with your application, then you are only allowed to distribute versions released by the author. This is
to maintain a single distribution point for the source code.
}

//Up to 255 COM ports are supported so we iterate through all of them seeing
//if we can get the default configuration
for i:=1 to 255 do
begin
//Form the Raw device name
Port_Name := ‘COM’ + IntToStr(i);

if GetDefaultCommConfig(PChar(Port_Name), cc, my_dwSize) then
begin
combo_box.AddItem(Port_Name,Nil);
nb_ports := nb_ports +1;
end;
end;
// End of code snippet

if nb_ports = 0 then
MainApp.StatusBar.SimpleText := ‘No serial port detected!’
else
MainApp.StatusBar.SimpleText := IntToStr(nb_ports) + ‘ serial port(s) detected!’;
end;

This entry was posted in Software and tagged . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.