简体   繁体   中英

How can I output to the parent console window from a Win32 C++ application?

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.

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).

A GUI app does not have a console window attached to it by default.

When a GUI app is run from a console process, the GUI app can use AttachConsole() to attach itself to the console.

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() .

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).

Or, you can ignore cin / cout and just use ReadConsole() and WriteConsole() directly instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM