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

下面是具体代码
总共分为两个过程
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结束子进程
本文地址:[url]http://www.xszlo.com/article/2012-12-24/7746.html[/url],转发请保留这个地址,谢谢
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值