Windows – How to close windows by their handle

windowwindows

Does anyone know of an application which would close a window given its handle? Command line is good.

Note, that I do not wish to kill the respective application, rather a modal window owned by that application.

Rationale:

Sometime, a modal dialog is opened beneath the main window on my laptop. This happened not once for VS and Firefox. Very annoying.

I can locate the window with Spy++, but have no means of killing it.

EDIT:

An application allowing to send messages to an arbitrary window is good as well, I guess I can then send something like WM_CLOSE or whatever.

EDIT:

I wish to stress, that I am not interesting in closing a visible window. The whole point is to deal with ugly abnormalities when a modal dialog gets open beneath the owning window, which did happen and not once for me while working with VS and Firefox. So, the desired solution is to close a window by its handle or, if it could specifically locate obscured windows and bring them forth.

Best Answer

Okay, I made a small app that does the trick.

Screenshot

You can download it here.

Usage:

  1. Start the program
  2. Hold your mouse over the window you want to close (don't click on it)
  3. Press delete.

It sends a wm_close to the window under the mouse cursor.

Delphi code below...

unit uCloseWindow;

interface

uses
  Windows, Forms, Messages, SysUtils, Variants, Classes, Controls;

type
  TfrmMain = class(TForm)
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
  public
  end;

var
  frmMain: TfrmMain;

implementation

{$R *.dfm}

procedure TfrmMain.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  HandleUnderCursor:HWND;
begin
  if Key=VK_DELETE then
  begin
    HandleUnderCursor := WindowFromPoint(Mouse.CursorPos);
    SendMessage(HandleUnderCursor,WM_CLOSE,0,0)
  end;
end;

end.
Related Question