Know the window handle, how do I know the file name? Delphi/Windows SDK/API
Http://www.delphi2007.net/DelphiAPI/html/delphi_20061108114249281.html
Know the window handle, how to get this Program File Name ???
First, get the PID of the process to which the window belongs through getwindowthreadprocessid, and then obtain the file name of the process by enumerating the system process. The enumeration process can be performed through APIS such as system snapshots: createconlhelp32snapshot, process32first, and process32next.
Details
Uses tlhelp32;
Function crngetexefilefromwindow (hwin: hwnd): string;
VaR
Dwpid: DWORD;
Strexepath: string;
Ptoolhelp: thandle;
PE: tprocessentry32;
Me: tmoduleentry32;
Bok: bool;
Begin
Getwindowthreadprocessid (hwin, @ dwpid );
// Create a System Snapshot
Ptoolhelp: = createconlhelp32snapshot (th32cs_snapall, dwpid );
// Obtain the path of the executable file
If win32platform <> ver_platform_win32_nt then // Win9x
Begin
Zeromemory (@ PE, sizeof (PE ));
PE. dwsize: = sizeof (PE );
Bok: = process32first (ptoolhelp, PE );
While (Bok) Do
Begin
If PE. th32processid = dwpid then
Begin
Strexepath: = PE. szexefile;
Break;
End;
Bok: = process32next (ptoolhelp, PE );
End;
End
Else // winnt
Begin
Zeromemory (@ me, sizeof (me ));
Me. dwsize: = sizeof (me );
Module32first (ptoolhelp, me );
Strexepath: = me. szexepath;
End;
Closehandle (ptoolhelp );
Result: = strexepath;
End;
Procedure tform1.button1click (Sender: tobject );
VaR
Hwin: thandle;
Begin
// Replace it with the window handle you want to query. I randomly specify a value.
Hwin: = thandle ($008c0302 );
Showmessage (crngetexefilefromwindow (hwin ));
End;
Thank you.