unit ugetwindows;

{$mode delphi}

interface

uses
  Classes, SysUtils, windows;

Type
  TWindowRec = class
    hnd: HWND;
    Title, ClassName: String;
    constructor Create( xhnd: HWND;  xTitle, xClassName: string );
  end;

  TWindowsRecsLst = class( TList )
    constructor Create;
    function Locate( palabraTitulo, palabraClase: string ): TWindowRec;
    procedure Free;
  end;


function Get_Window_Handle( palTitulo, palClase: string ): HWND;
procedure Close_Window( ahwnd: HWND );

implementation
var
    resLst: TList;



function Get_Window_Handle( palTitulo, palClase: string ): HWND;
var
  wl: TWindowsRecsLst;
  awr: TWindowRec;
begin
  wl:= TWindowsRecsLst.Create;
  awr:= wl.Locate( palTitulo, palClase );
  if awr <> nil then
    result:= awr.hnd
  else
   result:= 0;
  wl.Free;
end;


procedure Close_Window( ahwnd: HWND );
begin
  if ahwnd <> 0 then
   SendMessage( ahwnd, WM_CLOSE, 0, 0 );
end;

constructor TWindowRec.Create( xhnd: HWND;  xTitle, xClassName: string );
begin
 inherited Create;
 hnd:= xhnd;
 Title:= xTitle;
 ClassName:= xClassName;
end;


function EnumWindowsProc(WHandle: HWND; LParM: LParam): LongBool;StdCall;Export;
var
    Title,ClassName:array[0..128] of char;
    sTitle,sClass:String;
    aWRec: TWindowRec;

begin
 Result:=True;

 GetWindowText(wHandle, Title,128);
 GetClassName(wHandle, ClassName,128);

 sTitle:=Title;
 sClass:=ClassName;


 if IsWindowVisible(wHandle) then
 begin
      aWRec:= TWindowRec.Create( whandle, sTitle, sClass );
      resLst.add( awrec );
      writeln( IntToStr( whandle )+': '+sTitle+'('+ sClass+')' );
 end;
end;

constructor TWindowsRecsLst.Create;
begin
  inherited Create;
  resLst:= self;
  EnumWindows(@EnumWindowsProc,0);
end;


procedure TWindowsRecsLst.Free;
var
  k: integer;
begin
 for k:= 0 to count -1 do
   TWindowRec( items[k]).Free;
 inherited Free;
end;


function TWindowsRecsLst.Locate( palabraTitulo, palabraClase: string ): TWindowRec;
var
  k: integer;
  buscando: boolean;
  awr: TWindowRec;
begin
 k:= 0;
 buscando:= true;
 while buscando and ( k < count ) do
 begin
   awr:= items[k];
   if ( pos( palabraTitulo, awr.Title ) > 0 ) and ( pos( palabraClase, awr.ClassName ) > 0 ) then
     buscando:= false
   else
     inc( k );
 end;
 if buscando then
  result:= nil
 else
  result:= awr;
end;

end.

