2
votes

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?

2
I think you can get the requested STDOUT with Use [GetStartupInfo()][1]. Not sure how it works with GUI applications, but it's worth a try. If it's set or is a file, you need to write there instead of your console. [1]: msdn.microsoft.com/en-us/library/ms683230%28v=vs.85%29.aspxkichik
I'm assuming you meant "runs as a GUI app with command line arguments..."?MSN

2 Answers

2
votes

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.txt to 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, AttachConsole will fail, and when this happens, you should call AllocConsole as before.

1
votes

I think your problem is handled by the code in this question of mine: Where do writes to stdout go when launched from a cygwin shell, no redirection

(My question is about a wierd corner case)