Vladivarius Vladivarius - 4 months ago 70
C++ Question

C++ Windows: How to close a console window?

I have a console window opened using AllocConsole(), besides the main Win32 window. The console window opens before the main one.

When I close the main window and the program returns from main function, the console remains open(and so does the process). It actually gets stuck somewhere in ntdll, as the debugger shows on pausing the program from Visual Studio 2012.

Closing it by clicking on the X button exits the process, but closing it with FreeConsole() doesn't, the process remains working windowless. CloseWindow(GetConsoleWindow()) doesn't close it, it minimizes it (!?!). PostMessage(GetConsoleWindow(),WM_QUIT,0,0) closes the window but the process still remains working(visually this is the same as FreeConsole().

Occasionally the program exits in the right way, but clicking on the X button works every time.

How do I do the same thing that clicking on the X button does?


Use PostMessage(wnd, WM_CLOSE, 0, 0) to close the console window, but the problem is probably somewhere else in your program even if this works as a hotfix. The console window should close/disappear automatically when you return from your main() or WinMain().