How to output to stdout from an MFC program

By Stephen Kellett
31 January, 2017

If you’ve ever developed an MFC program with a graphical user interface and then later thought that it would be really nice to also provide a command line version with output to stdout you’ve probably bumped into the problem that there is no stdout for these programs. The program isn’t attached to a console.

So how do you do it?

The secret to this is a Win32 API “AttachConsole” which is available from Windows XP onwards.
AttachConsole takes one argument, a DWORD identifying the process to which to attach. In our case we want to attach to the parent process, so we pass ATTACH_PARENT_PROCESS which is defined as (DWORD)-1.

AllocConsole(ATTACH_PARENT_PROCESS);

When you need to print to this console use _cprintf(), which is defined in conio.h.

But we’re still working with legacy systems!

If you need your code to work on old systems as well as modern systems you’ll need to use GetProcAddress() as shown below.

#ifndef ATTACH_PARENT_PROCESS
#define ATTACH_PARENT_PROCESS	((DWORD)-1)
#endif	//ATTACH_PARENT_PROCESS

typedef BOOL (WINAPI *AttachConsole_FUNC)(DWORD);

//-NAME---------------------------------
//.DESCRIPTION..........................
//.PARAMETERS...........................
//.RETURN.CODES.........................
//--------------------------------------

BOOL attachToProcessConsole(DWORD	processId)
{
    HMODULE				hMod;

    hMod = GetModuleHandle(_T("Kernel32.dll"));
    if (hMod != NULL)
    {
        AttachConsole_FUNC	func;

        func = (AttachConsole_FUNC)GetProcAddress(hMod, "AttachConsole");
        if (func != NULL)
        {
            // valid for Windows XP onwards

            return (*func)(processId);
        }
    }

    // out of luck, this operating system doesn't support AttachConsole();

    return FALSE;
}

Fully functional, free for 30 days