码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2014-10-18 15:21:27      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:blog   io   os   ar   for   div   on   cti   log   

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.  

  

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

标签:blog   io   os   ar   for   div   on   cti   log   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!