Terminating processes with delphi

Windows processes can be terminated from a delphi application using Win32 API calls. To terminate processes not owned by the current user the SE_DEBUG_NAME privilege must be set for the current process.

All sample code must include unit TlHelp32.

Sample code for activating SE_DEBUG_NAME privilege

function NTSetPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean;
var
  hToken: THandle;
  TokenPriv: TOKEN_PRIVILEGES;
  PrevTokenPriv: TOKEN_PRIVILEGES;
  ReturnLength: Cardinal;
begin
  Result := True;
  // Only for Windows NT/2000/XP and later.
  if not (Win32Platform = VER_PLATFORM_WIN32_NT) then
    Exit;

  Result := False;

  // obtain the processes token
  if OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
  begin
    try
      // Get the locally unique identifier (LUID) .
      if LookupPrivilegeValue(nil, PChar(sPrivilege),TokenPriv.Privileges[0].Luid) then
      begin
        TokenPriv.PrivilegeCount := 1; // one privilege to set

        case bEnabled of
          True: TokenPriv.Privileges[0].Attributes  := SE_PRIVILEGE_ENABLED;
          False: TokenPriv.Privileges[0].Attributes := 0;
        end;

        ReturnLength := 0; // replaces a var parameter
        PrevTokenPriv := TokenPriv;

        // enable or disable the privilege
        AdjustTokenPrivileges(hToken, False, TokenPriv, SizeOf(PrevTokenPriv),PrevTokenPriv, ReturnLength);
      end;
    finally
      CloseHandle(hToken);
    end;
  end;

  // test the return value of AdjustTokenPrivileges.
  Result := GetLastError = ERROR_SUCCESS;
  if not Result then
    raise Exception.Create(SysErrorMessage(GetLastError));
end;</pre>
<span style="text-decoration: underline;">Sample code for terminating processes by name of executable file</span>
<pre lang="delphi">procedure Killprocess(Name:String);
var
  PEHandle,hproc: cardinal;
  PE: ProcessEntry32;
begin
  NTSetPrivilege(SE_DEBUG_NAME,True);
  PEHandle := CreateTOOLHelp32Snapshot(TH32cs_Snapprocess,0);
  if PEHandle &lt;&gt; Invalid_Handle_Value then
  begin
    PE.dwSize := Sizeof(ProcessEntry32);
    Process32first(PEHandle,PE);

    repeat
      if Lowercase(PE.szExeFile) = Lowercase(Pchar(Name)) then
      begin
        hproc := openprocess(Process_Terminate,false,pe.th32ProcessID);
        TerminateProcess(hproc,0);
        closehandle(hproc);
      end;
    until Process32next(PEHandle,PE)=false;
  end;
  closehandle(PEHandle);
end;