Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
    
Alt-Tab usually brings the modal dialog back on top. –  Remus Rusanu Aug 26 '09 at 18:59
    
Well, not in my scenarios. It only does so if the modal dialog is open with a certain window style (do not remember exactly) which makes the dialog appear in the task bar. –  mark Aug 26 '09 at 20:36
add comment

migrated from stackoverflow.com Aug 29 '09 at 0:14

This question came from our site for professional and enthusiast programmers.

5 Answers

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.
share|improve this answer
    
Not good. Like I said the window is hidden behind another window. The whole purpose it tackle these ugly cases. –  mark Aug 27 '09 at 6:24
    
See the second EDIT in my post. –  mark Aug 27 '09 at 6:27
2  
No, you said it was "beneath" another window (implying y-position), and you didn't mention that the window was not visible. It's a bit rude of you to downvote after the effort i made to help you out. –  Wouter van Nifterick Aug 27 '09 at 8:21
    
On second thought, you are right. I should have explained myself better. You can downvote my question in return, because of this absense of clarity in it, I deserve it fairly. –  mark Aug 27 '09 at 9:07
    
There is no reason to downvote this answer. It is a valid programming answer to a not so programming related question. Reciprocal downvoting is hardly productive. –  Sinan Ünür Aug 27 '09 at 10:18
add comment

Press Alt + Esc to send the current foreground window to the back. Keep pressing this until you come to the dialog. This will cycle through even windows not in the Alt + Tab list.

share|improve this answer
add comment

I took this as an excuse to try out the Win32API for Ruby.

require 'Win32API'

WM_CLOSE = 0x0010
FindWindow = Win32API.new('user32', 'FindWindow', ["P", "P"], "L")
SendMessage = Win32API.new('user32', 'SendMessage', ["L", "L", "P", "P"], "L")

def Send_WM_CLOSE(title)
  handle = FindWindow.call(nil, title)
  SendMessage.call(handle, WM_CLOSE, nil, nil) if handle != 0
end

if ARGV[0].to_i==0
  title=String.new(ARGV[0])
  Send_WM_CLOSE(title)
else
  SendMessage.call(ARGV[0].to_i, WM_CLOSE, nil, nil)
end

Using this you can close a fresh notepad with

> ruby closewindow.rb "Untitled - Notepad"

or if you know the handle

> ruby closewindow.rb 15794730
share|improve this answer
    
Nice, but I am not going to install ruby for that :-) –  mark Aug 26 '09 at 20:42
    
There is a one-click installer, in case you change your mind. rubyforge.org/projects/rubyinstaller –  Jonas Elfström Aug 26 '09 at 21:42
add comment

Here is a Perl script to do that:

#!/usr/bin/perl

use strict;
use warnings;

use Win32::GuiTest qw(FindWindowLike SendKeys SetForegroundWindow);

die "Need pattern to match against window titles\n" unless @ARGV;
my ($windowtitle) = @ARGV;

my ($myhandle) = FindWindowLike(0, qr/winclose\.pl/);

my @windows = FindWindowLike(0, qr/\Q$windowtitle\E/i);

for my $handle ( @windows ) {
    next if $handle == $myhandle;
    SetForegroundWindow($handle);
    SendKeys("%{F4}");
}

And here is some entertainment using such a script (please do not consider this spam, I am just trying to illustrate a use of Perl's Win32::GuiTest: http://www.youtube.com/watch?v=BAg7K_uwNZs

share|improve this answer
    
Cute. But I do not feel like installing perl just for this. –  mark Aug 27 '09 at 6:29
add comment

This would be mind-numbingly simple to cook up for yourself. I see you've rejected Perl. What's your favorite language?

Here's a simple C example (not tested, going from memory):

#include <windows.h>
#include <stdio.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){
    HWND hWnd;

    if(!sscanf(lpCmdLine, "%i", &hWnd)){
        MessageBox(null, "Invalid argument", "Close Window", MB_OK | MB_ICONERROR);
        return 1;
    }

    PostMessage(hWnd, WM_CLOSE, 0, 0);
}

This is a simple C# example (again, not tested):

using System;
using System.Runtime.Interop;

static class Program{
    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    static extern int PostMessage(int hWnd, int msg, int wParam, int lParam);

    const int WM_CLOSE = 16;

    static void Main(string[] args){
        int hWnd;
        if(args.Length == 1 && int.TryParse(args[0], out hWnd))
            PostMessage(hWnd, WM_CLOSE, 0, 0);
        else MessageBox.Show("Invalid Argument", "CloseWindow", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
share|improve this answer
    
You are right. I was wondering if there are more user friendly solutions. Although, I have mentioned simple command line is good enough, usually one expects some nifty UI which lets you select the window, tells you all kind of info about it, etc... As of now, I still have to pair it with Spy++. But you are right nonetheless. –  mark Aug 27 '09 at 6:33
    
Making it into a GUI wouldn't take much more, except for a small investment in time. Spy++'s drag-a-target-and-highlight-a-window behavior is pretty easy to duplicate with an appropriate icon and cursor. The window-highlighting is easily done with the WinAPI functions GetWindowRgn and FrameRgn. There are other API functions that will give you whatever info about the window you're looking for. And SetWindowPos can be used to bring the target dialog to the top of the Z order so you can see it and interact with it instead of just closing it. –  P Daddy Aug 27 '09 at 12:12
    
Everything is easy and everything takes time we do not have. Why invent a wheel if it is probably already invented? I know how this works, you develop a little nifty utility for self usage, then you extend it, then you debug it to fix bugs and one easily finds itself wasting a couple of days on something already done and tested by others. –  mark Aug 28 '09 at 19:11
    
You've got a good point. But on the other hand, in a case like this, I believe more time might be spent searching for an existing solution than building one. Not every esoteric need is already satisfactorily met by an existing product—a fact to which I owe my prosperity. –  P Daddy Aug 28 '09 at 20:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.