That code can't possibly work as you propose. For one thing, you can't determine parent/child relationships using EnumProcesses(). It only gives you a flat array of all the running process IDs at that moment, there is no guarantee as to their order in the array. Second, you are simply looking for the caller's passed-in PID in the array, and when found then you are opening a HANDLE to that process and querying its PID - the same PID that you already have! GetProcessId() does not give you a parent PID.
The only APIs I am aware of that can provide you with a parent PID are:
CreateToolhelp32Snapshot() + Process32(First|Next)()
NtQueryInformationProcess()
So, for example, using Toolhelp32:
function GetParentProcessID(const AProcessID: DWORD): DWORD;
var
hSnapshot: THandle;
pe: PROCESSENTRY32;
begin
Result := 0;
hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if hSnapshot <> INVALID_HANDLE_VALUE then
try
pe.dwSize := SizeOf(dwSize);
if Process32First(hSnapshot, pe) then
repeat
if pe.th32ProcessID = AProcessID then
begin
Result := pe.th32ParentProcessID;
Exit;
end;
until not Process32Next(hSnapshot, pe);
finally
CloseHandle(hSnapshot);
end;
end;
Or, using NTDLL:
function GetParentProcessID(const AProcessID: DWORD): DWORD;
var
hProcess: THandle;
pbi: PROCESS_BASIC_INFORMATION;
begin
Result := 0;
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, AProcessID);
if hProcess <> 0 then
try
if NtQueryInformationProcess(hProcess, ProcessBasicInformation, @pbi, SizeOf(pbi), nil) = STATUS_SUCCESS then
Result := DWORD(pbi.InheritedFromUniqueProcessId);
finally
CloseHandle(hProcess);
end;
end;