I have a C++ Win32 application that runs as a console app if run with command line arguments, but as a windowed app if there are no command line arguments. I do it using this method to create a console using AllocConsole() and STD_OUTPUT_HANDLE:
http://www.halcyon.com/~ast/dload/guicon.htm
My entry point is wWinMain (unicode WinMain).
It almost works great. If I run app.exe param1, I get the console and no GUI window. If I run app.exe with no parameters, it fires up the GUI and moves merrily along with no console.
There’s one thing missing.
If I run app.exe param1 > output.txt, the stdout output is not redirected to the output.txt file. It gets lost along the way. Is there a way to have a hybrid app like I have and still preserve any command-line redirects?
Try to call AttachConsole first with
ATTACH_PARENT_PROCESS(value -1) as its argument. That will redirect your app to the console it has been run from, and therefore allow the> output.txtto obtain whatever it outputs. Otherwise, the output isn’t caught because two different consoles are used – the one your app has been run from, and the one it has created. The redirection to the file works on the first, while your app outputs to the second.Edit: The above is correct assuming your app is run with arguments from an existing console (cmd.exe or so). However, this might not always be the case – it might be run with arguments from a shortcut, task scheduler, another process etc. When this is the case,
AttachConsolewill fail, and when this happens, you should callAllocConsoleas before.