当前位置:Gxlcms > mysql > 通过进程句柄关闭某个程序的进程

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

时间:2021-07-01 10:21:17 帮助过:73人阅读

下面是具体代码 总共分为两个过程 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,转发请保留这个地址,谢谢

人气教程排行