1

If I use this...

[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

...to get the instance of the console in my C# .Net4.5 Console app and assign it to a variable (which I pass as the hWnd parameter in a call to user32's MessageBox() method), do I need to call kernel32's CloseHandle() method when I'm done with the unmanaged variable?

When I try this, I get an SEHException, which my google searches seem to indicate has something to do with Debug mode and earlier versions of .NET.

Question 1 - Should I use CloseHandle, or just leave it and let the console resource resolve itself?

Question 2 - Is the SEHException completely unrelated, or is it because I'm trying to close console when it's still instantiated?


Side Note

Apologies for the "noob question"; I have next to zero experience with unmanaged code.

I know there are better ways to do this; I am deliberately trying to do it without importing Windows.Forms

Riegardt Steyn
  • 5,431
  • 2
  • 34
  • 49
  • That depends on what the `IntPtr` holds. The title of the question is a bit vague. According to the body, no, you shouldn't use `CloseHandle()`. But according to the title, the only reasonable answer is "maybe." – cdhowie Aug 19 '14 at 17:01
  • 1
    It is a window handle, they are never closed or released. The lifetime of a window is entirely determined by the window itself. It cannot be kept alive artificially, the handle simply becomes invalid when the underlying window is closed by the user. Do not try to release it. – Hans Passant Aug 19 '14 at 18:08

1 Answers1

3

You should never call CloseHandle on a window handle. The correct way to close a window is to call DestroyWindow. CloseHandle should be called to close handles to kernel objects, e.g. file handles, process handles, etc. A window handle is a GDI object, so it wouldn't be closed by CloseHandle.

However DestroyWindow will close the window as if you clicked on the close button. So to answer your root question, no you do not need to close the window handle in your code. That is unless you want to close the console window.

shf301
  • 31,086
  • 2
  • 52
  • 86
  • Thanks for the info... interestingly enough, when you use CloseWindow it doesn't actually close the console window, but it does minimize it?! – Riegardt Steyn Aug 20 '14 at 08:51
  • 1
    @Heliac - CloseWindow is documented as minimizing the window. It's DestroyWindow to close a window. I have no idea when CloseWindow would minimize a window. See http://msdn.microsoft.com/en-us/library/windows/desktop/ms632678(v=vs.85).aspx – shf301 Aug 20 '14 at 14:38