I want to find the executer app of my Delphi app.
For example, if a file named "a.exe" executes another file "b.exe" then "b.exe" should show "a.exe" in a message.
I wrote a Delphi program like this:
uses
...PsApi, TlHelp32;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function FindParentProcess(): String;
end;
var
Form1: TForm1;
//Boolean
ParentProcessFound: Boolean;
//DWORD
CurrentProcessID, ParentProcessID: DWORD;
//String
ParentProcessPath, WhichParentProcess: String;
//THandle
HandleParentProcess, HandleSnapShot: THandle;
//TProcessEntry32
EntryParentProcess: TProcessEntry32;
implementation
{$R *.dfm}
function TForm1.FindParentProcess;
const
BufferSize = 4096;
begin
ParentProcessFound := False;
HandleSnapShot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if HandleSnapShot <> INVALID_HANDLE_VALUE then begin
EntryParentProcess.dwSize := SizeOf(EntryParentProcess);
if Process32First(HandleSnapShot, EntryParentProcess) then begin
CurrentProcessID := GetCurrentProcessId();
repeat
if EntryParentProcess.th32ProcessID = CurrentProcessID then begin
ParentProcessID := EntryParentProcess.th32ProcessID;
HandleParentProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, ParentProcessID);
if HandleParentProcess <> 0 then begin
ParentProcessFound := True;
SetLength(ParentProcessPath, BufferSize);
GetModuleFileNameEx(HandleParentProcess, 0, PChar(ParentProcessPath), BufferSize);
CloseHandle(HandleParentProcess);
end;
break;
end;
until not Process32Next(HandleSnapShot, EntryParentProcess);
end;
CloseHandle(HandleParentProcess);
end;
if ParentProcessFound then begin
Result := ParentProcessPath;
end else begin
Result := '';
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
WhichParentProcess := FindParentProcess;
ShowMessage(WhichParentProcess);
end;
end.
And I wrote a program (test.exe) which will execute my Delphi app:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
ShellExecute(NULL, "open", "Project1.exe", NULL, NULL, SW_NORMAL);
return 0;
}
But the problem is Project1.exe shows itself (Project1.exe) instead of "test.exe".
How to detect which application run my Delphi program?