Mega Code Archive

 
Categories / Delphi / Examples
 

Reterive installed comports

Title: Reterive installed comports Question: I want to know what comports that is installed in a system. I also want to check if the comport is availible and free to use. Answer: // Use GetcomPortList to reterive a list of installed Comport is the system. // Calling with "AOnlyAvail = true" will reterive a list containing only // comports that is free and availible to use. // // Example: GetComPortList(Listbox1.Items,true); // // You will need Registry & Windows in your uses clause. // // For more information about Comports and how to use it: // Check the Comport project on sourceforge // http://sourceforge.net/projects/comport function ValidateComPort(ComPort : PChar) : boolean; var PortHandle : THandle; begin PortHandle := CreateFile(ComPort,GENERIC_READ OR GENERIC_WRITE,0,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); if (PortHandle = INVALID_HANDLE_VALUE) then begin result := false; end else begin result := true; CloseHandle(PortHandle); end; end; procedure GetComPortList(AList : TStrings; AOnlyAvail : boolean = false); var AReg : TRegistry; ADeviceList : TStrings; lp0 : integer; AAddPort : boolean; ACurrPort : string; begin if Assigned(AList) then begin AReg := TRegistry.Create; try AReg.RootKey := HKEY_LOCAL_MACHINE; AReg.OpenKeyReadOnly('hardware\devicemap\serialcomm'); ADeviceList := TStringList.Create; try AReg.GetValueNames(ADeviceList); AList.Clear; for lp0 := 0 to ADeviceList.Count-1 do begin ACurrPort := AReg.ReadString(ADeviceList.Strings[lp0]); if AOnlyAvail then begin AAddPort := ValidateComPort(PChar(ACurrPort)); end else AAddPort := true; if AAddPort then AList.Add(ACurrPort); end; finally ADeviceList.Free; end; AReg.CloseKey; finally AReg.free; end; end; end;