windows 如何在 GUI 应用程序中写入控制台
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/192294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write to the console in a GUI application
提问by Colen
Background: We develop win32 applications, and use the "Thompson Toolkit" on windows to give us a unix-like shell that we use as our command-line.
背景:我们开发了 win32 应用程序,并在 windows 上使用“Thompson Toolkit”为我们提供了一个类似 unix 的 shell,用作我们的命令行。
We have a GUI program (with a WinMain and message loop) that we want to write to the console, but printf and so on don't work, even when we launch the program from the console. How can we write to the console from a GUI program? We need to print text there so that an automated build system can display error messages and so on.
我们有一个想要写入控制台的 GUI 程序(带有 WinMain 和消息循环),但是 printf 等不起作用,即使我们从控制台启动程序。我们如何从 GUI 程序写入控制台?我们需要在那里打印文本,以便自动构建系统可以显示错误消息等。
Thanks.
谢谢。
回答by Roel
In short, you need to attach a console. For details and ready to use code, see http://www.codeproject.com/KB/dialog/ConsoleAdapter.aspx.
简而言之,您需要附加一个控制台。有关详细信息和准备使用的代码,请参阅http://www.codeproject.com/KB/dialog/ConsoleAdapter.aspx。
回答by ejgottl
Instead of logging to the console, log to a file and then track the file with a separate gui application. This keeps the console uncluttered and gives you a more persistent record of your log, which occasionally is extremely useful. There are various libraries which will do most of this for you, or you can keep it simple and just do it yourself.
不要登录到控制台,而是登录到一个文件,然后使用单独的 gui 应用程序跟踪该文件。这使控制台保持整洁,并为您提供更持久的日志记录,这有时非常有用。有各种库可以为您完成大部分工作,或者您可以保持简单并自己完成。
回答by bkausbk
Basicly you have to create a console by your self with AllocConsole
, AttachConsole
. After that you have to get standard handles with GetStdHandle
and "associates a C run-time file descriptor with an existing operating-system file handle" with help of _open_osfhandle
.
基本上你必须自己创建一个控制台,AllocConsole
, AttachConsole
。之后,您必须获得标准句柄,GetStdHandle
并借助_open_osfhandle
.
The returned handle can be used to overwrite crt stdin
and stdout
. After that all crt methods like printf
should work.
返回的句柄可用于覆盖 crtstdin
和stdout
. 之后,所有 crt 方法都printf
应该可以工作。
回答by Ronny Brendel
somewhere in the Visual Studio Project Settings you can switch on having a console, assuming you are using VS. (Can't say where because I currently don't have it)
假设您使用的是 VS,您可以在 Visual Studio 项目设置中的某处打开控制台。(不能说在哪里,因为我目前没有)