我写了这个实用程序(exe),可以在这个宿主应用程序中调用它.我更喜欢它只能从主机应用程序调用该实用程序.从外部或其他主机运行它应立即终止该实用程序.
有没有办法找出哪个进程启动了我的实用程序?
谢谢你的回复.
您可以使用CreateToolhelp32Snapshot函数枚举正在运行的进程列表,然后使用Process32First函数来获取th32ParentProcessID,它是创建此进程(其父进程)的进程的标识符.
看这个例子.
uses
Psapi,
Windows,
tlhelp32,
SysUtils;
function GetTheParentProcessFileName(): String;
const
BufferSize = 4096;
var
HandleSnapShot : THandle;
EntryParentProc : TProcessEntry32;
CurrentProcessId: DWORD;
HandleParentProc: THandle;
ParentProcessId : DWORD;
ParentProcessFound : Boolean;
ParentProcPath : String;
begin
ParentProcessFound := False;
HandleSnapShot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //enumerate the process
if HandleSnapShot <> INVALID_HANDLE_VALUE then
begin
EntryParentProc.dwSize := SizeOf(EntryParentProc);
if Process32First(HandleSnapShot, EntryParentProc) then //find the first process
begin
CurrentProcessId := GetCurrentProcessId(); //get the id of the current process
repeat
if EntryParentProc.th32ProcessID = CurrentProcessId then
begin
ParentProcessId := EntryParentProc.th32ParentProcessID; //get the id of the parent process
HandleParentProc := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, ParentProcessId);
if HandleParentProc <> 0 then
begin
ParentProcessFound := True;
SetLength(ParentProcPath, BufferSize);
GetModuleFileNameEx(HandleParentProc, 0, PChar(ParentProcPath),BufferSize);
ParentProcPath := PChar(ParentProcPath);
CloseHandle(HandleParentProc);
end;
break;
end;
until not Process32Next(HandleSnapShot, EntryParentProc);
end;
CloseHandle(HandleSnapShot);
end;
if ParentProcessFound then
Result := ParentProcPath
else
Result := '';
end;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2798 次 |
最近记录: |