Posts tagged ‘process’

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

  1. function NTSetPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean;
  2. var
  3. hToken: THandle;
  4. TokenPriv: TOKEN_PRIVILEGES;
  5. PrevTokenPriv: TOKEN_PRIVILEGES;
  6. ReturnLength: Cardinal;
  7. begin
  8. Result := True;
  9. // Only for Windows NT/2000/XP and later.
  10. if not (Win32Platform = VER_PLATFORM_WIN32_NT) then
  11. Exit;
  12.  
  13. Result := False;
  14.  
  15. // obtain the processes token
  16. if OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
  17. begin
  18. try
  19. // Get the locally unique identifier (LUID) .
  20. if LookupPrivilegeValue(nil, PChar(sPrivilege),TokenPriv.Privileges[0].Luid) then
  21. begin
  22. TokenPriv.PrivilegeCount := 1; // one privilege to set
  23.  
  24. case bEnabled of
  25. True: TokenPriv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
  26. False: TokenPriv.Privileges[0].Attributes := 0;
  27. end;
  28.  
  29. ReturnLength := 0; // replaces a var parameter
  30. PrevTokenPriv := TokenPriv;
  31.  
  32. // enable or disable the privilege
  33. AdjustTokenPrivileges(hToken, False, TokenPriv, SizeOf(PrevTokenPriv),PrevTokenPriv, ReturnLength);
  34. end;
  35. finally
  36. CloseHandle(hToken);
  37. end;
  38. end;
  39.  
  40. // test the return value of AdjustTokenPrivileges.
  41. Result := GetLastError = ERROR_SUCCESS;
  42. if not Result then
  43. raise Exception.Create(SysErrorMessage(GetLastError));
  44. end;

Sample code for terminating processes by name of executable file

  1. procedure Killprocess(Name:String);
  2. var
  3. PEHandle,hproc: cardinal;
  4. PE: ProcessEntry32;
  5. begin
  6. NTSetPrivilege(SE_DEBUG_NAME,True);
  7. PEHandle := CreateTOOLHelp32Snapshot(TH32cs_Snapprocess,0);
  8. if PEHandle <> Invalid_Handle_Value then
  9. begin
  10. PE.dwSize := Sizeof(ProcessEntry32);
  11. Process32first(PEHandle,PE);
  12.  
  13. repeat
  14. if Lowercase(PE.szExeFile) = Lowercase(Pchar(Name)) then
  15. begin
  16. hproc := openprocess(Process_Terminate,false,pe.th32ProcessID);
  17. TerminateProcess(hproc,0);
  18. closehandle(hproc);
  19. end;
  20. until Process32next(PEHandle,PE)=false;
  21. end;
  22. closehandle(PEHandle);
  23. end;