如何从Windows应用程序写入控制台窗口?

如何从Windows应用程序写入控制台窗口?

问题描述:

您是否曾经想过如何从Windows应用程序写出一个单独的控制台窗口而不是写一个日志文件?出于多种原因,您可能需要这样做-主要与调试有关.

Ever wondered how you could write out to a separate console window from your Windows application rather than writing to a log file? You might need to do that for a number of reasons – mostly related to debugging.

要以编程方式执行此操作,可以P调用适当的Win32控制台功能(例如 AttachConsole 来使用另一个您自己的代码中的流程).这样,您可以最好地控制实际发生的情况.

To do this programmatically, you can PInvoke the appropriate Win32 console functions (e.g. AllocConsole to create your own or AttachConsole to use another process's) from within your own code. This way you have the best control over what actually happens.

如果可以在整个过程的整个生命周期中与其他UI一起打开控制台窗口,则可以在Visual Studio中简单地更改项目属性,然后选择控制台应用程序",就像这样:

If you are OK with having a console window open alongside your other UI for the full lifetime of your process, you can simply change the project properties from within Visual Studio and choose "Console Application", simple as that: