Need help with close another application

Question

I got a code that displays active application names inside a listbox. Is it possible to close the selected application name inside the listbox? Thx..Here are the codes..

Function EnumWindowsProc (Wnd: HWND; lb: TListbox): BOOL; stdcall;
var
  caption: Array [0..128] of Char;
begin
  Result := True;
  if IsWindowVisible(Wnd) and ((GetWindowLong(Wnd, GWL_HWNDPARENT) = 0) or
   (HWND(GetWindowLong(Wnd, GWL_HWNDPARENT)) = GetDesktopWindow)) and
   ((GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_TOOLWINDOW) = 0) then   

begin
     SendMessage( Wnd, WM_GETTEXT, Sizeof( caption ),integer(@caption));
     lb.Items.AddObject( caption, TObject( Wnd ));
   end;
end;

procedure TMainForm.GetButtonClick(Sender: TObject);
begin
   listbox1.clear; // clear the list box
   EnumWindows( @EnumWindowsProc, integer(listbox1)); //get the programs
end;

Answer

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);
var
  H: HWND;
begin
  H := FindWindow(nil, 'Calculator');
  if H <> 0 then
    PostMessage(H, WM_CLOSE, 0, 0)
  else
    ShowMessage('Calculator not found');
end;