C win32 api – GetStdHandle(STD_OUTPUT_HANDLE) is invalid, very perplexing

cwinapi

I have the following fragment in my WinMain and I am launching this GUI app from the console. I want to redirect output to the console from which my app was launched.I am getting the "The handle is invalid." error after GetStdHandle().

However, if I use AllocConsole instead of AttachConsole, it works fine. In addition, if I use STD_ERROR_HANDLE instead of STD_OUTPUTHANDLE then fprintf(stderr, "errror") works fine.

I saw a blog entry which had the same problem but no solution. I am using vc 2010 compiler on 64 bit windows 7.

Thanks!

bConsole = AttachConsole(ATTACH_PARENT_PROCESS) != FALSE;

if (bConsole)
{
    int fd = 0;
    long lStdOut;
    lStdOut = (long)GetStdHandle(STD_OUTPUT_HANDLE);
    fd = _open_osfhandle(lStdOut, _O_TEXT);
    if (fd > 0)
    {
        *stdout = *_fdopen(fd, "w");
        setvbuf(stdout, NULL, _IONBF, 0 );
    }
}
printf("Test!!!!!!!!!!!!");

Best Answer

AttachConsole does associate your process with a console, but stdout has already been opened (and connected to the old handle, whatever it was).

Overwriting stdout directly is a terrible idea. Instead, you must freopen("CONOUT$", "w", stdout); to get stdout going to the console.

But there are a lot of other little details. Have a look at my question Where do writes to stdout go when launched from a cygwin shell, no redirection which covers your problem in the question, then asks a question about some corner cases. Finally there's a code sample which incorporates everything.

Related Topic