2006. július 19., szerda

Kill an application without any confirmation


Problem/Question/Abstract:

How to kill an application without any confirmation

Answer:

The following code searches for Notepad, and kills it - no questions asked. Use

WinHwnd := FindWindow(classname, nil);

or

WinHwnd := FindWindow(nil, 'window-caption');

with your apps details.

procedure TForm1.ButtonClick(Sender: TObject);
var
  ProcessHandle: THandle;
  WinHwnd: HWND;
  ProcessID, ExitCode: Integer;
begin
  ProcessID := 0;
  ExitCode := 0;
  WinHwnd := FindWindow('NotePad', nil);
  if not (IsWindow(WinHwnd)) then
  begin
    ShowMessage('NotePad not found');
    exit;
  end;
  GetWindowThreadProcessID(WinHwnd, @ProcessID);
  ProcessHandle := OpenProcess(PROCESS_CREATE_THREAD or PROCESS_VM_OPERATION
    or PROCESS_VM_WRITE or PROCESS_VM_READ or
    PROCESS_TERMINATE, False, ProcessID);
  if (ProcessHandle > 0) then
  begin
    GetExitCodeProcess(ProcessHandle, ExitCode);
    { or  GetExitCodeProcess(ProcessHandle, DWORD(ExitCode)); }
    TerminateProcess(ProcessHandle, ExitCode);
    CloseHandle(ProcessHandle);
  end
  else
    ShowMessage('Unable to get proccess Handle');
end;

Nincsenek megjegyzések:

Megjegyzés küldése