Search This Blog

Friday, July 17, 2009

Allocating a Console Window to a Win32 WIndows Application

Intro.
For some reasons or for easier Debugging you may sometimes need a console Window on a Windows Application (There is OutputDebugString() for easier debugging in Output window) But some people still love console debugging ;)


How to.

The Windows function AllocConsole() will help you to allocate a console Window with a Win32/MFC/Windows Forms Application.

Code.

AllocConsole();

freopen("conin$", "r", stdin);
freopen("conout$", "w", stdout);

cout<<"Testing :) ";

Well, the above code snippet allocates a console Window to a Win32 Windows application, and freopen() reassigns the standard input/output streams to our attached console window. Now you can use the standard Input/Output features of C/C++ like printf(), scanf(), cin, cout etc with your newly attached console window :)

PS : A process can be associated with only one console, so the AllocConsole function fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its current console, then it can call AllocConsole to create a new console or AttachConsole to attach to another console.
If the calling process creates a child process, the child inherits the new console.


-MSDN.

No comments:

Post a Comment