Link to home
Start Free TrialLog in
Avatar of davizinx
davizinxFlag for Brazil

asked on

Get window title from a process

I would get the title of the window of the iexplore.exe process.
Important: it is not the active window, you get directly from the process!

any solution ?
Avatar of Geert G
Geert G
Flag of Belgium image

use process explorer from www.sysinternals.com
Once you had the PID of the process you would enumerate all the windows and match it.

Something like this:


type
  PProcessID = ^TProcessID;
  TProcessID = record
    PID : DWORD;
    Title : String[255];
  end;
 
function GetWindowNameFromPID(PID: DWORD): String;
var
  ProcessID : PProcessID;
begin
  GetMem(ProcessID,SizeOf(TProcessID));
  ProcessID^.PID := PID;
  If Not EnumWindows(@EnumProcess,Pointer(ProcessID)) Then
    begin
    If MessageDlg('Could not get hook to the process handles.' + #13#10 + 'Try Again?',mtConfirmation,[mbYes,mbNo],0) = mrYes Then
      begin
      GetWindowNameFromPID(PID);
    end;
  end;
end;
 
function EnumProcess(Handle: HWND; lParam: Integer): BOOL; stdcall;
var
  PID : Cardinal;
  ProcessID : TProcessID;
  Title : String;
begin
  If Handle = NULL Then
    begin
    Result := False;
  end
  Else
    begin
    ProcessID := PProcessID(Pointer(lParam))^;
    GetWindowThreadProcessID(Handle,PID);
    If ProcessID.PID = lParam Then
      begin
      SetLength(Title,255);
      SetLength(Title,GetWindowText(Handle,PChar(Title),Length(Title)));
      If Title = '' Then
        begin
        Title := 'Empty';
      end;
      ProcessID.Title := Title;
    end;
    Result := True;
  end;
end;

Open in new window

A process can have several windows.  You would like to get a list of all the captions, I presume.
^ This is true. The code I posted will get the last window title. It can be modified to shove them in an array.
Avatar of davizinx

ASKER



[Error] Unit1.pas(64): Incompatible types: 'Integer' and 'Pointer'

for

If Not EnumWindows(@EnumProcess,Pointer(ProcessID)) Then
ASKER CERTIFIED SOLUTION
Avatar of ThievingSix
ThievingSix
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ThievingSix:

Thanks for reply, i try this code:

Label1.caption:= GetWindowNameFromPID(3688); //3688 = firefox

and i try with anothers process and dont work.
the label is blank, do not show the window name.
please post your entire routine in which the error occurs.

I think it might be easier to insert into a TStringList variable than an array.