Get Active Window Title - Delphi

DarkCoderSc
Jean-Pierre LESUEUR
uses
System.SysUtils, Winapi.Windows;
// ...
function ActiveWindowTitle() : String;
begin
result := '';
///
var AWindow : THandle := GetForegroundWindow();
if AWindow = 0 then
raise EWindowsException.Create('GetForegroundWindow');
var ACaptionLen := GetWindowTextLengthW(AWindow);
if ACaptionLen = 0 then
Exit(); // Possibly empty caption
// Include terminating NULL characters
Inc(ACaptionLen);
var ACaptionSize := ACaptionLen * SizeOf(WideChar);
var pBuffer : PWideChar;
GetMem(pBuffer, ACaptionSize);
try
if GetWindowTextW(AWindow, pBuffer, ACaptionLen) = 0 then
raise EWindowsException.Create('GetWindowTextW');
///
result := String(pBuffer);
finally
FreeMem(pBuffer, ACaptionSize);
end;
end;
// ...
WriteLn(ActiveWindowTitle());
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.
Implemented By Technique
Featured Windows APIs
Created
April 15, 2025
Last Revised
April 17, 2025