How to get the executable file name from a window handle?

Viewed 623

I have this code:

procedure TForm1.Button1Click(Sender: TObject);
var
  MyHandle: THandle;
begin
  MyHandle:=FindWindow(nil, 'Delphi');
  SendMessage(MyHandle, WM_CLOSE, 0, 0);
 // Here will be a message like ' title found and it's test.exe that has 'Delphi' Title
end;

For example, it is test.exe that is the process that has the 'Delphi' title, and I want to get the EXE file name of that process by using the window handle. Is that possible? If so, may I have some reference for doing it?

2 Answers

Here is a procedure which I use, which you are likely to find in other places on the internet. I don't recall the exact source, it may have been https://www.swissdelphicenter.ch.

uses
  Windows, TlHelp32, ...

function WindowHandleToEXEName(handle : THandle) : string;
var
  snap : THandle;
  pe : tagPROCESSENTRY32;
  pid : THandle;
  found : boolean;
begin
  Windows.SetLastError(ERROR_SUCCESS);

  result := '';
  if (handle = 0) then exit;

  snap := TLHelp32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if (snap = Cardinal(-1)) then exit;

  Windows.GetWindowThreadProcessId(handle, @pid);
  pe.dwSize := Sizeof(pe);
  found := TLHelp32.Process32First(snap, pe);

  while found do
  begin
    if (pe.th32ProcessID = pid) then
    begin
      result := String(pe.szExeFile);
      break;
    end;
    found := TLHelp32.Process32Next(snap, pe);
  end;
  CloseHandle(snap);
end;
Related