Sunday, January 30, 2011

Adding Console into GUI applications

Tip - To add Console into a GUI application (Dialog based, SDI or MDI), use AllocConsole() and freopen(). AllocConsole() allocates a new console for the calling process.

Details - While debugging an application it is often useful to have trace output window for data logging rather than using MessageBox or OutputDebugString. An easiest method is to create a console window and redirect standard I/O to it like the following:

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

After this, all printf and cout calls will output to the console window.

Even input will work for it. We can use getch() from conio.h to pause a thread. 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. This function is primarily used by graphical user interface (GUI) application to create a console window. The standard input handle is a handle to the console's input buffer and the standard output and standard error handles are handles to the console's screen buffer.

Reference   -

Posted By :Jijo Krishnan

No comments:

Post a Comment