在程序中能否像系统杀死进程那样杀死一个正在去行的程序??(30分)

  • 主题发起人 主题发起人 青梅
  • 开始时间 开始时间
1.列举进程
procedure TForm1.rzbtnListClick(Sender: TObject);
var
I : Integer;

LAProcess, LAModule: array[0..1023] of Cardinal;
hProcess : THandle;
LLi : TListItem;
cNeeded, cProcess : DWORD;
begin
rzlvProcess.Clear;
if not EnumProcesses(@LAProcess, SizeOf(LAProcess), cNeeded) then
exit; //error
rzlvProcess.Items.BeginUpdate;
try
for I := 0 to cNeeded div SizeOf(DWORD) - 1 do // Iterate
begin
if LAProcess = 0 then Continue;
hProcess := OpenProcess({PROCESS_ALL_ACCESS, //}
PROCESS_QUERY_INFORMATION or PROCESS_VM_READ,
False, LAProcess);
if (hProcess <> 0) and (
EnumProcessModules(hProcess, @LAModule, SizeOf(LAModule),
cProcess)) then
begin
LLi := rzlvProcess.Items.Add;
LLi.Caption := IntToHex(LAProcess, 4);//记下PID
LLi.SubItems.Add(MyGetModuleBaseName(hProcess, LAModule[0]));//进程可执行程序名字
LLi.SubItems.Add(MyGetModulePath(hProcess, LAModule[0]));//位置
CloseHandle(hProcess);
end;
end; // for
finally
rzlvProcess.Items.EndUpdate;
end;
end;
2. 杀死进程,根据PID
procedure TForm1.rzbtnEndTaskClick(Sender: TObject);
var
hProcess : THandle;
Msg : string;
begin
with rzlvProcess do
begin
if Selected <> nil then
begin
Msg := 'PID: ' + Selected.Caption + ' Name: ' + Selected.SubItems[0]
+ #13'End Task ?';
if IDYES = MessageBox(Application.Handle, Pchar(Msg), 'Query',
MB_YESNO or MB_ICONINFORMATION or MB_APPLMODAL or MB_DEFBUTTON2)
then
begin
hProcess := OpenProcess(PROCESS_TERMINATE,
False, StrToInt('$' + rzlvProcess.Selected.Caption));
//rzlvProcess.Selected.Caption 上一个函数记下的进程 PID
if (hProcess <> 0) then
begin
TerminateProcess(hProcess, 0);
CloseHandle(hProcess);
end;
end;
end;
end;
end;

function TForm1.MyGetModuleBaseName(hProcess: THandle;
hModule: HMODULE): string;
begin
SetLength(Result, MAX_PATH);
SetLength(Result,
GetModuleBaseName(hProcess, hModule, @Result[1], MAX_PATH));
end;

function TForm1.MyGetModulePath(hProcess: THandle;
hModule: HMODULE): string;
begin
SetLength(Result, MAX_PATH);
SetLength(Result,
GetModuleFileNameEx(hProcess, hModule, @Result[1], MAX_PATH));
Result := ExtractFilePath(Result);
end;
 
后退
顶部