function KillTask(ExeFileName: string): integer;
const
PROCESS_TERMINATE=$0001;
var
ContinueLoop: BOOL;
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;
end;
begin
killtask(edit1.text);
end;
第一种情况也是最简单情况的就是提供确定的[*“确定的”加着重号*]“lpWindowName”参数,如下例:
procedure TForm1.CloseAppClick(Sender: TObject);//确定标题
var Exehandle:Thandle;
begin
//获得句柄-->标题确定
ExeHandle:=findWindow(nil,'文件管理器');//返回句柄
//关闭程序
if ExeHandle<>0 then
SendMessage(ExeHandle,WM_Close,0,0)
else
Application.MessageBox('没有打开“文件管理器”!','提示',
MB_IconInformation+MB_OK);
end;
另一种情况是程序窗体没有确定的[*“没有确定的”加着重号*]标题,这就是很多朋友出现疑问的
地方,也是几乎所有参考书均不涉及的地方。比如打开“写字板”程序,它的标题会随着文本文件
名的不同而不同,此时,你要关闭它,就不得不提供程序的类名,但是如何获得程序的类名呢?笔
者在这里向大家介绍一个可行的办法:首先打开程序(此处以“记事本”为例),然后,运行
WinSight32(Delphi自带)或Spy++(VC自带),找到程序(“记事本”)的运行状态,即可找到我
们需要的类名(两者均为“Class Name”项)。参考一个例子:
procedure TForm1.CloseVAppClick(Sender: TObject);//标题不确定
var ExeHandle:Thandle;
begin
//获得句柄-->标题不确定
ExeHandle:=FindWindow('notepad',nil);//'');//返回句柄
//关闭程序
if ExeHandle<>0 then
SendMessage(ExeHandle,WM_Close,0,0)
else
Application.MessageBox('没有打开“记事本”程序!','提示',
MB_IconInformation+MB_OK);
end;
当然,既能提供程序的类名又能提供程序窗体的标题自然就没有讨论的必要了。