Maison  >  Article  >  base de données  >  通过进程句柄关闭某个程序的进程

通过进程句柄关闭某个程序的进程

WBOY
WBOYoriginal
2016-06-07 15:30:481787parcourir

下面是具体代码 总共分为两个过程 EnumProcTree 主要用来枚举句柄树 KillProc 关闭 某个 程序 的 进程 procedure EnumProcTree(const PID: DWORD; out PID_Tree: TPIDTree); procedure ListTree(RootPID: DWORD); var hP_Root: THandle; Found: Boolean; Pn:

下面是具体代码 
总共分为两个过程 
EnumProcTree 主要用来枚举句柄树 
KillProc 关闭某个程序进程 


procedure EnumProcTree(const PID: DWORD; 
  out PID_Tree: TPIDTree); 

  procedure ListTree(RootPID: DWORD); 
  var 
    hP_Root: THandle; 
    Found: Boolean; 
    Pn: TProcesseNtry32; 
    hSnap: THandle; 
  begin 
    hP_Root := OpenProcess(PROCESS_ALL_ACCESS, False, RootPID); 
    if hP_Root 0 then 
    begin 
      CloseHandle(hP_Root); 

      SetLength(PID_Tree, Length(PID_Tree) + 1); 
      PID_Tree[Length(PID_Tree) - 1] := RootPID; 

      hSnap := CreateToolHelp32SnapShot(TH32CS_SNAPPROCESS, 0); 
      Pn.dwSize := SizeOf(TProcesseNtry32); 
      Found := Process32First(hSnap, Pn); 
      while Found do 
      begin 
        if RootPID = Pn.th32ParentProcessID then 
        begin 
          ListTree(Pn.th32ProcessID); 
        end; 
        Found := Process32Next(hSnap, Pn); 
      end; 
      CloseHandle(hSnap); 
    end; 
  end; 
begin 
  SetLength(PID_Tree, 0); 
  ListTree(PID); 
end; 

KillProc过程的参数: 
PID需要结束的句柄ID 
Killchild是否结束子进程 

如果KillChild是True,那么首先枚举所有的子句柄,然后一次性都关闭 
procedure KillProc(PID: DWORD; Killchild: Boolean = True; const ExitCode: Cardinal = 0); 
var 
  i: integer; 
  hProc: THandle; 
  PID_Tree: TPIDTree; 
begin 
  if Killchild then 
  begin 
    EnumProcTree(PID, PID_Tree); 

    for i := High(PID_Tree) downto Low(PID_Tree) do 
    begin 
      if (PID_Tree[i] 0) then 
      begin 
        hProc := OpenProcess(PROCESS_ALL_ACCESS, False, PID_Tree[i]); 
        if hProc 0 then 
        begin 
          TerminateProcess(hProc, ExitCode); 
          CloseHandle(hProc); 
        end; 
      end; 
    end; 
  end 
  else 
  begin 
    hProc := OpenProcess(PROCESS_ALL_ACCESS, False, PID); 
    if hProc 0 then 
    begin 
      TerminateProcess(hProc, ExitCode); 
      CloseHandle(hProc); 
    end; 
  end; 
end; 

使用代码 
KillProc(lpProcessInformation.dwProcessId, True, Result); 

lpProcessInformation.dwProcessId 进程的句柄ID 
True结束子进程 
本文地址:http://www.xszlo.com/article/2012-12-24/7746.html,转发请保留这个地址,谢谢

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn