Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Puertos COM libres/ocupados??? (https://www.clubdelphi.com/foros/showthread.php?t=39961)

vejerf 02-02-2007 20:57:24

Puertos COM libres/ocupados???
 
Buenas tardes...
os expongo mi problema a ver si podeis ayudarme... que seguro q si...
pues bien tengo una aplicacion que debe recoger datos de los puertos serie y tengo q hacerlo genérico, es decir, independiente del número de puertos COM que tenga el ordenador... y la pregunta es...
existe algún método que me diga que puertos COM tengo en mi ordenador y cuales están libres/ocupados???
Muchas gracias a tod@s...

seoane 02-02-2007 21:52:41

Se me ocurren un par de formas de hacerlo.

Una es consultando la entrada del registro:
Código:

HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
Es decir:
Código Delphi [-]
uses Registry;

procedure GetPortList(List: TStringList);
var
  i: integer;
begin
  List.Clear;
  with TRegistry.Create do
  try
    RootKey:= HKEY_LOCAL_MACHINE;
    Access:= KEY_READ;
    if OpenKey('HARDWARE\DEVICEMAP\SERIALCOMM',FALSE) then
    begin
      GetValueNames(List);
      for i:= List.Count - 1 downto 0 do
        List[i]:= ReadString(List[i]);
      CloseKey;
    end;
  finally
    Free;
  end;
end;


// Por ejemplo para mostrarlo en un combobox
var
  List: TStringList;
begin
  List:= TStringList.Create;
  try
    GetPortList(List);
    // El Combobox se llama Combobox1
    Combobox1.Items.Assign(List);
  finally
    List.Free;
  end;
end;

Ahora sería interesante saber si el puerto esta ocupado:
Código Delphi [-]
function Ocupado(Puerto: String): Boolean;
var
  Handle: THandle;
begin
  Handle:= CreateFile(PChar('\\.\' + Puerto),GENERIC_READ or GENERIC_WRITE,0,
    nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
  if Handle <> INVALID_HANDLE_VALUE then
  begin
    CloseHandle(Handle);
    Result:= FALSE;
  end else
    Result:= TRUE;
end;

// Siguiendo el ejemplo anterior, solo mostramos los libres
var
  List: TStringList;
  i: integer;
begin
  List:= TStringList.Create;
  try
    GetPortList(List);
    Combobox1.Items.Clear;
    for i:= 0 to List.Count - 1 do
      if not Ocupado(List[i]) then
        Combobox1.Items.Add(List[i]);
  finally
    List.Free;
  end;
end;

Pero ya que tenemos una función que nos dice si un puerto esta disponible, por que no la usamos también para listar los puertos. Solo tenemos que comprobar un numero razonable de puertos, aquí uso 10 pero si lo crees necesario usa 100.
Código Delphi [-]
// Otra vez el mismo Combobox
var
  i: integer;
begin
  Combobox1.Clear;
  for i:= 0 to 10 do
    if not Ocupado('COM' + IntToStr(i)) then
      Combobox1.Items.Add('COM' + IntToStr(i));
end;


La franja horaria es GMT +2. Ahora son las 13:59:45.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi