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.
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)
Basicly you have to create a console by your self with
AllocConsole
,AttachConsole
. After that you have to get standard handles withGetStdHandle
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
andstdout
. After that all crt methods likeprintf
should work.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.
In short, you need to attach a console. For details and ready to use code, see http://www.codeproject.com/KB/dialog/ConsoleAdapter.aspx.