unit FunKP;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Tlhelp32;
type
TForm1 = class(TForm)
ListBox1: TListBox;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//函数
function KillProcess(ProcessName: PChar): Boolean;
const
PROCESS_TERMINATE = $0001;
var
Snap: THandle;//存放CreateToolhelp32Snapshot()
PE: TProcessEntry32;//存放PROCESSENTRY32结构
Lp: Boolean;//存放Process32First()、Process32Next()
Op: THandle;//存放OpenProcess()
begin
Result := False;
snap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);//获得进程快照
if snap <= 0 then begin
Exit;
end;
PE.dwSize := SizeOf(TProcessEntry32);//为dwSize赋值
Lp := Process32First(snap,PE);//枚举当前的进程
while Lp do begin
if PE.szExeFile = ProcessName then//进程名与szExeFile比较
begin
Op := OpenProcess(PROCESS_TERMINATE,False,PE.th32ProcessID);//打开句柄
Result := TerminateProcess(Op,0);//结束进程
end;
Lp := Process32Next(snap,PE);//枚举当前的进程
end;
CloseHandle(snap);//关闭句柄
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
//调用函数
ListBox1.Items.Add('程序开始运行');
if KillProcess('notepad.exe') then begin
ListBox1.Items.Add('结束进程notepad.exe成功');
end else begin
ListBox1.Items.Add('结束进程notepad.exe失败');
end;
end;
end.