本帖最后由 冥界3大法王 于 2019-12-9 13:05 编辑
无费话,说重点!
[Delphi] 纯文本查看 复制代码 procedure TForm1.Button1Click(Sender: TObject);
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
Tlhelp32;
const
PROCESS_TERMINATE = $0001;
var
ExeFileName: string;
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
ExeFileName := 'x32dbg.exe';
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
TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), FProcessEntry32.th32ProcessID), 0);
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
end;
这样呢? 成功结束进程了,但是想换另一个进程呢?再粘一遍?用8遍一样的代码?!
不好不好,还要更进一步,程序员得学会复用代码,马上想到用函数!重复利用才是王道。
[Delphi] 纯文本查看 复制代码 function KillProcess(s: string): string;
const
PROCESS_TERMINATE = $0001;
var
ExeFileName: string;
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
//ExeFileName := 'x32dbg.exe';
ExeFileName := s;
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
TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), FProcessEntry32.th32ProcessID), 0);
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
end;
然后我们再Button2调用
[Delphi] 纯文本查看 复制代码 procedure TForm1.Button2Click(Sender: TObject);
var
str1: string;
begin
str1 := 'x32dbg.exe';
KillProcess(str1);
end;
这样就做到了最小的开销,重复利用。 |