Search code examples
c++visual-studio-2010winapiwindows-console

How to add console window in Win32 Project, Visual Studio 2010


I'm going to add console window in Win32 Project, Visual Studio 2010. OS : Windows XP (x64 bit)

I'm going to debug some library which is developed with console project. I add this one in to my Win32 project.

Is there any solution to add console window in to Win32 Project ?


Solution

  • As mentioned in this blog post (which I found by typing "add console to win32 project" into Google), you can accomplish this with the following code:

    #include <stdio.h>
    #include <io.h>
    #include <fcntl.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(), ...
    }