Articles - Enumerating Windows in Delphi

'

This article was written by Peter Johnson. Peter has written a number of articles, components and applications.

The following is an example of using the Win32 'EnumWindows' call to retrieve the handle of all windows on the desktop. A call-back function 'GetWindows' is defined that puts the handle of each window into a 'TList' structure.

The code that follows retrieves the current window title of each one using 'GetWindowText' and modifies all windows with a title using 'SetWindowText'.

A more useful application of this technique is finding a top-level target window and then using the 'EnumChildWindows' call to retrieve all child windows. As Windows treats controls as child windows it is possible to retrieve a pointer to all the controls on a form and to send them messages. This is the technique used by my PhoneLift program to take control of the software. Messages are sent to the controls within the application that select the next record and the data can be retrieved because the window text of each label of the form contains the phone directory information.

unit EnumTest;

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

type
TForm1 = class(TForm)
  Button1: TButton;
  procedure Button1Click(Sender: TObject);
  Private
    { Private declarations }
  Public
    { Public declarations }
end;

var
  Form1: TForm1;
  WindowList: TList;

implementation

{$R *.DFM}

function GetWindows(Handle: HWND; Info: Pointer): BOOL; stdcall;
begin
  Result := True;
  WindowList.Add(Pointer(Handle));
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  TopWindow: HWND;
  Dest: array[0..80] of char;
  i: integer;
begin
  try
    WindowList := TList.Create;
    TopWindow := Handle;
    EnumWindows(@GetWindows, Longint(@TopWindow));
    for i := 0 to WindowList.Count - 1 do
    begin
      GetWindowText(HWND(WindowList[i]), Dest, sizeof(Dest) - 1);
      if StrLen(Dest) > 0 then
      begin
        StrPCopy(Dest, 'EnumTest!');
        SetWindowText(HWND(WindowList[i]), Dest);
      end;
    end;
    finally
      WindowList.Free;
    end;
  end;
end. 


Google
Web www.Delphi-Central.com
Delphi Central - Delphi Programming Tutorials, Hints and Tips