Need to get window caption when I only have the instance from GetModuleHandle

I have a DLL that I'm writing in Delphi and I need to be able to get the main window caption of the calling application.  I have no issue identifying the application using GetModuleFileName() and then using GetModuleHandle() to get the instance but I can't work out how to get any further.  Any assistance greatly appreciated :-)
aburgoyneAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
MerijnBConnect With a Mentor Sr. Software EngineerCommented:
Here it is in total:
function GetHwnd(ProcessID: DWORD): hwnd;
var WindowProcesID: DWORD;
begin
 result := GetWindow(GetDesktopWindow(), GW_CHILD);
 
 while result <> 0 do
 begin
  if IsWindowVisible(result) then
  begin
   GetWindowThreadProcessId(result, WindowProcesID);
   if ProcessID = WindowProcesID then
    break;
  end;
 
  result := GetWindow(result, GW_HWNDNEXT);
 end;
end;
 
procedure TForm2.Button1Click(Sender: TObject);
var WinHandle: hwnd;
    WindowText: string;
begin
 WinHandle := GetHwnd(GetCurrentProcessId());
 
 if WinHandle <> 0 then
 begin
  SetLength(WindowText, 255); // assume some length
  SetLength(WindowText, GetWindowText(WinHandle, @WindowText[1], Length(WindowText)));
  Label1.Caption := WindowText;
 end;
end;

Open in new window

0
 
MerijnBSr. Software EngineerCommented:
First you'll have to find it's window, using EnumWindows(),
after that you can get the caption with GetWindowText().

Need any help with that?
0
 
aburgoyneAuthor Commented:
Yes... lots probably!  I used Delphi quite a bit a few years back (D5) but haven't touched it for ages.
0
[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

 
aburgoyneAuthor Commented:
Haven't used EE for quite a while either ;-) ...forgot to ask if you could include a code snippet?
0
 
MerijnBSr. Software EngineerCommented:
Here's a function to find the window belonging to a process id:
function GetHwnd(ProcessID: DWORD): hwnd;
var WindowProcesID: DWORD;
begin
 result := GetWindow(GetDesktopWindow(), GW_CHILD);
 
 while result <> 0 do
 begin
  if IsWindowVisible(result) then
  begin
   GetWindowThreadProcessId(result, WindowProcesID);
   if ProcessID = WindowProcesID then
    break;
  end;
 
  result := GetWindow(result, GW_HWNDNEXT);
 end;
end;

Open in new window

0
 
MerijnBSr. Software EngineerCommented:
oops forgot: You can get your own processid by calling GetCurrentProcessID().

will post the rest soon
0
 
aburgoyneAuthor Commented:
Awesome! - works like a charm!

Thanks for all your help :-)
0
All Courses

From novice to tech pro — start learning today.