Delphi监视进程并结束进程

来源:互联网 发布:电脑摄像头软件 编辑:程序博客网 时间:2024/04/28 08:54
监视进程并结束进程在很多地方都用到这里借前人的经验写了个小例子:

以QQ的进程qq.exe为例

关键代码如下:


function CheckTask(ExeFileName: string): Boolean;
const
PROCESS_TERMINATE=$0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
result := False;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle,FProcessEntry32);
while integer(ContinueLoop) <> 0 do begin
       if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =UpperCase(ExeFileName))
       or (UpperCase(FProcessEntry32.szExeFile) =UpperCase(ExeFileName))) then
         result := True;
       ContinueLoop := Process32Next(FSnapshotHandle,FProcessEntry32);
end;
end;

function KillTask(ExeFileName:string):integer;
const
PROCESS_TERMINATE = $0001;
var
ContinueLoop: BOOLean;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
Result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) =
UpperCase(ExeFileName))) then
Result := Integer(TerminateProcess(
OpenProcess(PROCESS_TERMINATE,
BOOL(0),
FProcessEntry32.th32ProcessID),
0));
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
if CheckTask(’qq.exe’)=true then
KillTask(’qq.exe’)
else
Label1.Caption:=’进程不存在,监视中...’;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if CheckTask(’qq.exe’)=true then
Label1.Caption:=’进程正在运行中...’
else
Label1.Caption:=’进程不存在,监视中...’;
end;

转自:http://www.cnblogs.com/qq528/archive/2008/12/03/1346916.html

原创粉丝点击