如何从Win32 C ++应用程序输出到父控制台窗口? [英] How can I output to the parent console window from a Win32 C++ application?
问题描述
我有一个WinAPI / Win32应用程序。如果我在命令提示符下运行cin / cout / cerr时尝试使用它,则该方法不起作用。我尝试将项目类型从Windows应用程序切换为控制台应用程序,但是问题是当我通过双击可执行文件正常运行控制台窗口时出现。
I have a WinAPI/Win32 application. If I try to use cin/cout/cerr when it is run from a command prompt, it doesn't work. I tried switching the project type from Windows Application to Console Application, but the problem is that a console window appears when I run it normally by double-clicking the executable.
所以我的问题是:有什么办法可以在Win32应用程序的父(调用)控制台窗口中使用cin / cout / cerr? (我仅在传递参数 / c
或 /?
时才需要这种行为,因此,如果不带参数调用它那么无论它应该启动GUI是什么。)
So my question is: Is there any way I can use cin/cout/cerr with the parent (calling) console window in a Win32 application? (I only want this behaviour if parameter /c
or /?
were passed, so if it is called with no arguments then no matter what it should launch the GUI).
推荐答案
默认情况下,GUI应用未附加控制台窗口
A GUI app does not have a console window attached to it by default.
从控制台进程运行GUI应用程序时,GUI应用程序可以使用 AttachConsole()
将其自身附加到控制台。
When a GUI app is run from a console process, the GUI app can use AttachConsole()
to attach itself to the console.
或者,如果不是从控制台进程运行GUI应用程序,但仍想使用控制台窗口,则可以使用 AllocConsole()
。
Or, if the GUI app is not run from a console process, but still wants to use a console window, it can create its own console window using AllocConsole()
.
一旦将GUI应用程序附加到控制台,它便可以使用 GetStdHandle()
到g et处理控制台的STDIN / STDOUT,然后重定向 cin
/ cout
来使用它们(如何使用取决于您的
Once the GUI app is attached to a console, it can use GetStdHandle()
to get handles to the console's STDIN/STDOUT, and then redirect cin
/cout
to use them (how is dependent on your particular STL implementation).
或者,您可以忽略 cin
/ cout
,只需使用 ReadConsole()
和 WriteConsole()
直接。
Or, you can ignore cin
/cout
and just use ReadConsole()
and WriteConsole()
directly instead.
这篇关于如何从Win32 C ++应用程序输出到父控制台窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!