加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 确定当前应用程序的父进程

发布时间:2020-12-15 04:01:58 所属栏目:大数据 来源:网络整理
导读:我编写了这个实用程序(exe),可以在这个宿主应用程序中调用它. 我更喜欢只能从主机应用程序调用该实用程序. 从外部或其他主机运行它应立即终止该实用程序. 有没有办法找出哪个进程启动了我的实用程序? 谢谢你的回复. 解决方法 您可以使用 CreateToolhelp32Sn
我编写了这个实用程序(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,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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读