如何按名称杀死进程?

How to kill a process by name?

如何终止从给定进程名称开始的进程?

例如:如何杀死program.exe

我已经尝试了以下代码,其中 returns 进程名称从 PID 开始,但它不符合我的需要(在我的情况下,我有进程名称并且想要杀了它)

function GetPathFromPID(const PID: cardinal): string;
var
  hProcess: THandle;
  path: array[0..MAX_PATH - 1] of char;
begin
  hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, PID);
  if hProcess <> 0 then
    try
      if GetModuleFileNameEx(hProcess, 0, path, MAX_PATH) = 0 then
        RaiseLastOSError;
      result := path;
    finally
      CloseHandle(hProcess)
    end
  else
    RaiseLastOSError;
end;

您可以使用 this 函数按名称终止进程:

uses
  TlHelp32;

function KillTask(ExeFileName: string): Integer;
const
  PROCESS_TERMINATE = [=10=]01;
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;
  CloseHandle(FSnapshotHandle);
end;

注:

  • 可能有超过 1 个同名进程
  • KillTask函数returns杀死进程的计数
  • 我发现该函数的 page 说它适用于 Windows 9x/ME/2000/XP.
  • 我在 Windows 7/10
  • 亲自测试过

全部工作 windows。使用 FindWindow 单元 windows

KillTask('c:\my.cmd');

KillTask('caption');

procedure TForm1.KillTask(ExeFileName: string);
var
  H: HWND;
begin //ExeFileName = caption or cmd path
   H := FindWindow(nil, LPCWSTR(ExeFileName));
   if H <> 0 then
    PostMessage(H, WM_CLOSE, 0, 0);
end;