Articles Convert Delphi VCL window handle (HWND) To String by Scott Hollows

emailx45

Social Engineer
Joined
May 5, 2008
Messages
2,387
Reaction score
2,149
Convert Delphi VCL window handle (HWND) To String
[SHOWTOGROUPS=4,20]
Simple example of converting a window handle (HWND data type) to a string in a Delphi VCL program:
cardinal(vMyWindowHandle).ToString

This uses the WinApi.Windows unit

Example
Show the window handle of the foreground window
Code:
procedure TForm1.Button1Click(Sender: TObject);
var
   vMyWindowHandle : HWND;
begin
   vMyWindowHandle := GetForegroundWindow();  // get top most window

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

delphi_window_handle_to_string


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,
Code:
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

[/SHOWTOGROUPS]
 
Top