0

重複の可能性:
現在のアプリの親プロセスを決定する

プロセスの MainProcess ハンドルまたは PID を取得したいと考えています。たとえば、Google Chrome は、実際にはスレッドであるタブごとに別のプロセスをドロップします。ProcessExplorer では、ツリービューに chrome.exe がメインプロセスとして表示され、その下にスレッドが表示されます。MainProcess ハンドル/PID を確認または取得するにはどうすればよいですか? WindowsAPIのようなものですか?

ご協力いただきありがとうございます。

4

1 に答える 1

3

@RRUZ は、スタック オーバーフローに関するほぼ同じ質問に既に回答しています。ただし、プロセス ID を として宣言しているという点で、コードは正しくありませんTHandle。以下は、私が見つけた間違いを修正し、ファイル名ではなく PID を返すようにルーチンを適応させます。

uses
  Windows,
  tlhelp32,
  SysUtils;

function GetParentPid: DWORD;
var
  HandleSnapShot: THandle;
  EntryParentProc: TProcessEntry32;
  CurrentProcessId: DWORD;
  HandleParentProc: THandle;
  ParentProcessId: DWORD;
begin
  Result := 0;
  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
            Result := ParentProcessId;
            CloseHandle(HandleParentProc);
          end;
          break;
        end;
      until not Process32Next(HandleSnapShot, EntryParentProc);
    end;
    CloseHandle(HandleSnapShot);
  end;
end;

これは重複した質問であることは知っていますが、ここのコードはまさにOPが望んでいるものであるため、少なくともしばらくの間は表示したままにします.

于 2012-04-17T20:02:56.527 に答える