Re: Stop another program from Delphi app

Posted by webmaster Guido

In Reply to: Stop another program

: I know how to start another program with ShellExecute, but how can I stop an external program from inside my Delphi program?

Closing (stopping) an application can be done by closing its main window. That's done by sending a close- message to that window:

PostMessage(WindowHandle, WM_CLOSE, 0, 0);

You get the handle of a window with:

FindWindow(PointerToWindowClass, PointerToWindowTitle) 

If you provide only one of the two parameters, use NIL for the other one.

Here's some example code: try to stop the program with 'Calculator' in its title bar, and give a warning message if its window is not found:

procedure TForm1.Button1Click(Sender: TObject);
  H: HWND;
  H := FindWindow(nil, 'Calculator');
  if H <> 0 then
    PostMessage(H, WM_CLOSE, 0, 0)
    ShowMessage('Calculator not found');