本文整理自网络,侵删。
有时候,我们创建了一个子进程,我们需要知道自己所隶属的父进程的ID。有几个办法,一个是调用微软未公开的 NtQueryInformationProcess 函数,另一个就是下面提供的一个函数,利用了公开的函数,运行需要包含 tlhelp32 单元。
function GetParentProcessId: Cardinal;
var
hSnapshot: THandle;
AEntry: TProcessEntry32;
begin
Result := 0;
hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if hSnapshot <> INVALID_HANDLE_VALUE then
begin
try
AEntry.dwSize := sizeof(TProcessEntry32);
if Process32First(hSnapshot, AEntry) then
begin
repeat
if AEntry.th32ProcessID = GetCurrentProcessId then
begin
Result := AEntry.th32ParentProcessID;
break;
end;
until not Process32Next(hSnapshot, AEntry);
end;
finally
CloseHandle(hSnapshot);
end;
end;
end;
这个函数直接会返回当前的父进程的ID,如果找不到,返回0.
当然,根据上面的原因,你很容易就可以写出枚举所有子进程的函数了,这里就不再缀述了,大家可以根据自己的想法写写看。
相关阅读 >>
pos、ansipos、fillchar在Delphi2010中unicode的问题
更多相关阅读请进入《Delphi》频道 >>