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); var vMyWindowHandle : HWND; begin vMyWindowHandle := GetForegroundWindow(); // get top most window ShowMessage ('Window handle is ' + cardinal(vMyWindowHandle).ToString ); end;
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; begin result := cardinal(aHandle).ToString; end; procedure TForm1.Button1Click(Sender: TObject); var vMyWindowHandle : cardinal; // uses WinApi.Windows begin vMyWindowHandle := GetForegroundWindow(); ShowMessage ('The window handle is ' + HandleToString(vMyWindowHandle)); end;
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.
- 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
Leave a Reply