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!!!!!!!!!!!!");
GetStdHandle
. If it fails it will returnINVALID_HANDLE_VALUE
. Check for this and the callGetLastError
if necessary. Then tell us whatGetLastError
reports. – David HeffernanlStdOut
asintptr_t lStdOut;
instead of usinglong lStdOut;
. See msdn.microsoft.com/en-us/library/bdts1c9x.aspx – OlegHANDLE
– see GetStdHandle – David HeffernanGetStdHandle
returns aHANDLE
, but_open_osfhandle
useintptr_t
as input parameter. One have to make type casting, but in the code of the question one useslong
instead ofintptr_t
, but the size oflong
can be different from the size ofHANDLE
orintptr_t
(having the same size asHANDLE
). – Oleg