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.
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.
I checked all submitted solutions here and they didn't work for me. You can always create (or change to) a CONSOLE subsystem. However, if you want to enable writing to the Console from a WIN32 appliation, not classidfied as a CONSOLE application, this code will work. After calling this function, you can just use printf (or wprintf).
My code uses AllocConsole() and then AttachConsole(), pssing to it the current process ID (obtained by calling GetProcessID).
void enableConsole()
{
AllocConsole();
AttachConsole(GetCurrentProcessId());
HWND Handle = GetConsoleWindow();
freopen("CON", "w", stdout);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With