我想找到我的Delphi应用程序的执行器应用程序。
例如,如果名为“ a.exe”的文件执行另一个文件“ b.exe”,则“ b.exe”应在消息中显示“ a.exe”。
我这样编写了一个Delphi程序:
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.
然后我编写了一个程序(test.exe),它将执行我的Delphi应用程序:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
ShellExecute(NULL, "open", "Project1.exe", NULL, NULL, SW_NORMAL);
return 0;
}
但是问题是Project1.exe显示了自身(Project1.exe)而不是“ test.exe”。
如何检测运行我的Delphi程序的应用程序?