开发者

WIN32: Need Help With stdout Redirect on Hybrid Console + GUI App

I have a C++ Win32 appli开发者_开发知识库cation 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.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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜