根据进程名,查找并结束进程

unit Unit1;  
  
   
  
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 FindProcess(ProcessName: String): Boolean;  
var  
  Snap: THandle;  
  Lp: Boolean;  
  PE: TProcessEntry32;  
begin  
 Result := False;  
 snap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);  
 if snap <= 0 then begin  
  Exit;  
 end;  
 PE.dwSize := SizeOf(TProcessEntry32);  
 Lp := Process32First(snap,PE);  
 while Lp do begin  
  if PE.szExeFile = ProcessName then begin  
   Result := True;  
   Break;  
  end;  
 Lp := Process32Next(snap,PE);  
 end;  
 CloseHandle(snap);  
end;    
  
   
  
  
   
  
  
//函数  
function KillProcess(ProcessName: string): 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 FindProcess('notepad.exe') then begin  
  ListBox1.Items.Add('发现进程notepad.exe');  
  if KillProcess('notepad.exe') then begin  
   ListBox1.Items.Add('结束进程notepad.exe成功');  
  end else begin  
   ListBox1.Items.Add('结束进程notepad.exe失败');  
  end;  
 end else begin  
  ListBox1.Items.Add('未发现进程notepad.exe');  
 end;  
end;  
  
   
  
end.  

  

原文地址:https://www.cnblogs.com/qingsong/p/4033040.html