How to kill a process by name?

delphi, kill-process

Solution

You can use this function in order to kill a process by name:

uses
  TlHelp32;

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;
  CloseHandle(FSnapshotHandle);
end;

Note:

- There could be more than 1 process having the same name

- `KillTask` function returns the count of the killed processes

- The page where I've found the function says that it works on Windows 9x/ME/2000/XP.

- I've personally tested it on Windows 7/10

Problem

How can I kill a process starting from a given process name? For example: How can I kill `program.exe`? I've tried the following code which returns the process name starting from a `PID` but it doesn't fit for my needs (In my case I have the process name and want to kill it) ``` 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; ```

Original source