How to Open Console Window in a Win32 Application

When you create a basic main()-based application, you get the console window implicitly; but a typical WinMain()-based application does not open a console window – you have to allocate the console and to connect the I/O streams yourself.

Yet, this is not a thing you find described in manuals. Fortunately, it’s simple to do, and the code presented here can be used as-is in all your projects.

#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <windows.h>

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    AllocConsole();

    HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
    int hCrt = _open_osfhandle((long) handle_out, _O_TEXT);
    FILE* hf_out = _fdopen(hCrt, "w");
    setvbuf(hf_out, NULL, _IONBF, 1);
    *stdout = *hf_out;

    HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
    hCrt = _open_osfhandle((long) handle_in, _O_TEXT);
    FILE* hf_in = _fdopen(hCrt, "r");
    setvbuf(hf_in, NULL, _IONBF, 128);
    *stdin = *hf_in;

    // use the console just like a normal one - printf(), getchar(), ...
}

30 responses to “How to Open Console Window in a Win32 Application

  1. Oh I know this is a bit of a noob question. Is there anything I need to get rid of or delete from that code that may cause memory leaks?

  2. Thanks, it is great.
    But when I run the program in a console, I get an error. Can I avoid that ?
    cheers

  3. Great! That really helped me. I was searching for a way to make a Qt Application close the console on exit.

  4. I want to show some thanks to you just for rescuing me from this crisis. Just after checking throughout the world-wide-web and seeing basics that were not productive, I was thinking my entire life was well over. Living without the presence of answers to the problems you have resolved by way of your good site is a critical case, as well as those that might have in a negative way damaged my career if I hadn’t discovered your web page. Your own competence and kindness in playing with the whole thing was tremendous. I am not sure what I would’ve done if I had not come upon such a solution like this. It’s possible to at this moment look forward to my future. Thanks a lot very much for this high quality and amazing guide. I won’t be reluctant to suggest your web page to anyone who would like guide on this situation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s