Mit Hilfe der Funktion CreateToolHelp32Snapshot sollte es eigentlich funktionieren. Wenn man die Anwendung über den Explorer startet, ist der übergeordnete Process EXPLORER.EXE bei batch oder cmd CMD.EXE und beim Taskplaner SVCHOST.EXE.
Delphi-Quellcode:
uses
TlHelp32, Contnrs;
type
TProcInfoItem = class
private
Fth32ProcessID: cardinal;
FParentExeName: AnsiString;
public
property Th32ProcessID: cardinal read Fth32ProcessID write Fth32ProcessID;
property ParentExeName: AnsiString read FParentExeName write FParentExeName;
end;
function TForm1.GetParentProcessExeName: AnsiString;
var
hProcSnap: THandle;
Proc32: TProcessEntry32;
i: integer;
ProcInfoList: TObjectList;
ProcItem: TProcInfoItem;
CurrentProcId: Cardinal;
begin
Result:= '';
CurrentProcId:= GetCurrentProcessId;
ProcInfoList:= TObjectList.Create;
try
hProcSnap := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcSnap > 0) and (hProcSnap <> INVALID_HANDLE_VALUE) then
try
ZeroMemory(@Proc32, SizeOf(TProcessEntry32));
Proc32.dwSize := SizeOf(TProcessEntry32);
if Process32First(hProcSnap, Proc32) then
repeat
ProcItem:= TProcInfoItem.Create;
ProcItem.Th32ProcessID:= Proc32.th32ProcessID;
ProcItem.ParentExeName:= ExtractFileName(Proc32.szExeFile);
ProcInfoList.Add(ProcItem);
until not Process32Next(hProcSnap, Proc32) or (CurrentProcId= Proc32.th32ProcessID);
finally
CloseHandle(hProcSnap);
end;
for i:= ProcInfoList.Count- 1 downto 0 do
if TProcInfoItem(ProcInfoList.Items[i]).th32ProcessID= Proc32.th32ParentProcessID then
begin
Result:= TProcInfoItem(ProcInfoList.Items[i]).ParentExeName;
break;
end;
finally
ProcInfoList.Free;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ShowMessage(GetParentProcessExeName);
end;