C++ – Win32 application write output to console using printf

cwinapiwindows

I have an exe developed using win32 application. When I run (double click) the exe GUI should appear and when i call exe from command prompt output should appear in command console.

My issue is how can i redirect output to command window using printf? I am able to print in command window using AllocConsole(), but new command window is created and output is redirected to new window. I want to print output in same command window where exe is called using Win32 application. Any help appreciated.

Best Answer

To build on what wilx said (sorry I don't have enough reputation to just comment on his answer) you can use AttachConsole(...); So to attach to a console if an only if there is already one available you could use something like:

bool bAttachToConsole()
{
    if (!AttachConsole(ATTACH_PARENT_PROCESS))
    {
        if (GetLastError() != ERROR_ACCESS_DENIED) //already has a console
        {
            if (!AttachConsole(GetCurrentProcessId()))
            {
                DWORD dwLastError = GetLastError();
                if (dwLastError != ERROR_ACCESS_DENIED) //already has a console
                {
                    return false;
                }
            }
        }
    }

    return true;
}

Then in your WinMain you can do this:

if (bAttachToConsole())
{
    //do your io with STDIN/STDOUT
    // ....
}
else
{
    //Create your window and do IO via your window
    // ....
}

Additionally you will have to "fix" the c standard IO handles to use your new console see the following write up for a great example of how to do this.

Related Topic