Convert Delphi VCL window handle (HWND) To String

Simple example of converting a window handle (HWND data type) to a string in a Delphi VCL program


This uses the WinApi.Windows unit


Show the window handle of the foreground window

procedure TForm1.Button1Click(Sender: TObject);
   vMyWindowHandle : HWND;
   vMyWindowHandle := GetForegroundWindow();  // get top most window

   ShowMessage ('Window handle is '
               + cardinal(vMyWindowHandle).ToString


Use your own own conversion function

The conversion of a handle to cardinal number type is not guarenteed to work on all future versions of Windows.  For a “best practise” approach you should wrap the conversion code into a function so you can change the conversion code if needed,

function HandleToString (aHandle : HWND) : string;
  result := cardinal(aHandle).ToString;

procedure TForm1.Button1Click(Sender: TObject);
 vMyWindowHandle : cardinal; // uses WinApi.Windows
 vMyWindowHandle := GetForegroundWindow();
 ShowMessage ('The window handle is ' + HandleToString(vMyWindowHandle));

Tested Delphi Versions

Tested ok on Delphi 10.1 on Windows 7 32 bit and Windows 10 64 bit.
It should work with many other version of Delphi and Windows

Im sure this would not work prior to Delphi 2005 as it uses a record helper that was introduced in that version of Delphi.

If you can verify any other versions of Delphi / Windows please post a comment below

Other Conversion Methods

Try IntToStr and Format

+1 this post

Please help get this blog listed on DelphiFeeds by +1 voting here and also vote on BeginEnd.  Thank you.

About Me


  • Oracle & Delphi software developer based in Perth, Western Australia
  • Australian Delphi User Group – President and WA meeting organizer
  • Australian Oracle User Group – WA State Committee Member
  • Available to do remote presentations to user groups on Delphi and Oracle topics
blog email linkedinlogo


Published by

3 responses to “Convert Delphi VCL window handle (HWND) To String”

  1. Doesn’t IntToStr work anymore? Or Format? The latter even lets you turn it into a hex string.

  2. Thanks. Ive added those as alternatives

  3. Type helpers for cardinals were added in XE4, so cardinal.ToString will work in XE4 and later versions.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: