Get Window Caption / Title - Delphi

DarkCoderSc personal avatar
DarkCoderSc

Jean-Pierre LESUEUR

var ATargetWindow := 0 // Write here a known window handle

var ACaptionLength := GetWindowTextLength(ATargetWindow);
if (ACaptionLength = 0) and (GetLastError = 0) then
  raise EWindowsException.Create('GetWindowTextLength');

Inc(ACaptionLength);

var ACaption := '<Untitled>';
if ACaptionLength > 0 then begin
  SetLength(ACaption, ACaptionLength); // Alternatively to GetMem

  if GetWindowText(ATargetWindow, PWideChar(ACaption), ACaptionLength) = 0 then
    raise EWindowsException.Create('GetWindowText');
end;

// ...

WriteLn(ACaption);

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 25, 2025

Last Revised

April 25, 2025