Window Enumeration via EnumWindows - Delphi

DarkCoderSc personal avatar
DarkCoderSc

Jean-Pierre LESUEUR

uses
  System.SysUtils, Winapi.Windows, Generics.Collections;

// ...

type
  TWindowEnumParam = class
  private
    FList : TDictionary<THandle, String>;
  public
    {@C}
    constructor Create(const AList : TDictionary<THandle, String>);

    {@G}
    property List : TDictionary<THandle, String> read FList write FList;
  end;
  PWindowEnumParam = ^TWindowEnumParam;

constructor TWindowEnumParam.Create(const AList : TDictionary<THandle, String>);
begin
  inherited Create();
  ///

  FList := AList;
end;

// ...

function EnumWindowsProc(hWnd: HWND; lParam: LPARAM): BOOL; stdcall;
begin
  var ACaption := '';

  var ACaptionLen := GetWindowTextLengthW(hWnd) + 1;
  if ACaptionLen > 0 then begin
    SetLength(ACaption, ACaptionLen);

    GetWindowTextW(hWnd, PWideChar(ACaption), ACaptionLen);
  end;


  PWindowEnumParam(lParam).List.Add(hWnd, ACaption);

  ///
  Result := True;
end;

function EnumerateWindows(var AList : TDictionary<THandle, String>) : Cardinal;
begin
  result := 0;
  ///

  if not Assigned(AList) then
    AList := TDictionary<THandle, String>.Create()
  else
    AList.Clear();

  var AWindowEnumParam := TWindowEnumParam.Create(AList);

  if not EnumWindows(@EnumWindowsProc, NativeUInt(@AWindowEnumParam)) then
    raise EWindowsException.Create('EnumWindows');

  ///
  result := AList.Count;
end;

// ...

var AList := TDictionary<THandle, String>.Create();
try
  EnumerateWindows(AList);
  ///

  for var hWindow in AList.Keys do begin
    var ACaption := '';
    if not AList.TryGetValue(hWindow, ACaption) then
      continue;

    WriteLn(Format('(%d) %s', [
      hWindow,
      ACaption
    ]));
  end;

finally
  FreeAndNil(AList);
end;

Creating and researching code snippets takes time and effort. You’re welcome to share them through your own platforms, but please don’t forget to credit the original author, here: Jean-Pierre LESUEUR.


Created

April 24, 2025

Last Revised

April 24, 2025