Search code examples
c#console-applicationdllimportunmanagedresources

Should I use CloseHandle on a locally defined IntPtr variable?


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


Solution

  • 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.