7

Given a handle of a window, how can I close the window by using the window handle?

Maslow
  • 18,464
  • 20
  • 106
  • 193
user705414
  • 20,472
  • 39
  • 112
  • 155

3 Answers3

21

The easiest way is to use PInvoke and do a SendMessage with WM_CLOSE.

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

private const UInt32 WM_CLOSE          = 0x0010;

void CloseWindow(IntPtr hwnd) {
  SendMessage(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • This works about half the time for me. What's strange is that there are some Explorer windows that don't close. Instead, Explorer's address bar just goes blank and the window stays open. – Andrew Rondeau Aug 22 '19 at 19:48
  • @AndrewRondeau, I know this is a bit old, but, the behavior you describe could potentially be that you're acquiring/closing the wrong handle, perhaps? – Erick Brown Jun 24 '21 at 13:07
0

Not sure if there is another way but you could PInvoke the following:

                // close the window using API        
            SendMessage(iHandle, WM_SYSCOMMAND, SC_CLOSE, 0);
dice
  • 2,820
  • 1
  • 23
  • 34
-1

Call CloseWindow via P/Invoke:

http://www.pinvoke.net/default.aspx/user32.closewindow

Or DestroyWindow

http://www.pinvoke.net/default.aspx/user32/DestroyWindow.html

Andre Loker
  • 8,368
  • 1
  • 23
  • 36
  • The first link is a P/Invoke declaration for [`CloseWindowStation`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms682047(v=vs.85).aspx), which servers a different purpose. The caveat re [`DestroyWindow`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms632682(v=vs.85).aspx) is that it only works with windows created by the _same thread_. – mklement0 Jul 26 '18 at 16:44