How to write to the console in a GUI application

2019-01-19 17:48发布

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.

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.

Thanks.

4条回答
Deceive 欺骗
2楼-- · 2019-01-19 18:25

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)

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-19 18:35

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.

The returned handle can be used to overwrite crt stdin and stdout. After that all crt methods like printf should work.

查看更多
霸刀☆藐视天下
4楼-- · 2019-01-19 18:40

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.

查看更多
聊天终结者
5楼-- · 2019-01-19 18:47

In short, you need to attach a console. For details and ready to use code, see http://www.codeproject.com/KB/dialog/ConsoleAdapter.aspx.

查看更多
登录 后发表回答