Kawaii-Hachii
Kawaii-Hachii

Reputation: 1061

Get Window Title if I only have the PID (Process ID)

Using Delphi (in this case Delphi 7), how can I get Window Title from PID (process ID).

I am trying to capture the "Internet Explorer / Chrome" Window Title.

My code so far:

procedure GetAllBrowserTitle;
var
  hProcSnap    : THandle;
  pe32         : TProcessEntry32;
  P            : string;
  PID          : integer;
  ContinueLoop : BOOL;
begin

  try
    hProcSnap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if hProcSnap = INVALID_HANDLE_VALUE then exit;

    pe32.dwSize  := SizeOf(pe32);
    ContinueLoop := Process32First(hProcSnap, pe32);

    While (Integer(ContinueLoop) <> 0) do
    begin

      P := LowerCase(pe32.szExeFile);

      if (Pos('iexplore.exe', P) > 0) Or (Pos('chrome.exe', P) > 0) then
      begin
        PID   := pe32.th32ProcessID;
        // Get the Window Title
        // ???
      end;

      ContinueLoop := Process32Next(hProcSnap, pe32);
    end;

    CloseHandle(hProcSnap);

  except
  end;
end;

The part that I don't know is to get the Window Title. From my research, all examples requires Window Handle or using the EnumWindow callback which I am not quite understand.

Please if you can help.

Thanks.

Upvotes: 1

Views: 2394

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596196

Once you have a PID, there are 2 ways you can discover the windows it has created.

  1. Call EnumWindows() to enumerate all top-level windows. The callback function you pass to it can use GetWindowThreadProcessId() to check if each window belongs to the PID.

  2. Use CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD), Thread32First(), and Thread32Next() to enumerate all running threads, looking for ones that belong to the PID, calling EnumThreadWindows() on each matching thread.

Note that in both cases, you will be enumerating top-level windows only. If the target process creates child windows instead of top-level windows, especially with the intent of hosting those child windows in other windows of different processes, then you will have to use #1, but ignore the PID of the top-level windows and use EnumChildWindows() to enumerate their child windows, using GetWindowThreadProcessId() on the child windows instead.

Upvotes: 2

Related Questions