This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

| Dynamic Win32 Console Allocation Submitted by

Recently I wanted to use a console window to display some debug output for a Win32 program I was making with Visual Studio. Many sites on the internet recommend either creating a new project as a Win32 Console Application, or adding the _CONSOLE definition to your project and changing the /subsystem:console link setting to /subsystem:windows.
This might be fine for temporary debuging sessions or making a permenant console mode app, but I wasn't satisfied with this approach. I wanted the ability to create the console when I needed it, and to make the console go away when it was done. After a quick search on MSDN I found a set of functions that hasn't gotten much press but was exactly what I was looking for, so I thought I would share it you. Here is a small selection of the functions to get you started:

> - AllocConsole - Creates a new console for the calling process
> - FreeConsole - Detatches the calling process from its console
> - GetStdHandle - Retrieves handles that are equivelent to STDOUT, STDIN, STDERR
> - ReadConsole - Reads input data from the console and removes it from the buffer
> - WriteConsole - Writes a string to the console at the cursor position

The simplest example that I can give is:

     AllocConsole();
     HANDLE stdout ;
     DWORD count ;
     stdout = GetStdHandle( STD_OUTPUT_HANDLE );
     WriteConsole(stdout, "Test", 4, &count, NULL );
     FreeConsole();

I recommend looking at the MSDN pages for more information:
http://msdn.microsoft.com/library/en-us/fileio/hh/winbase/conchar_5ehx.asp

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.