简体   繁体   中英

C++ : Writing to a console which opened a form

I have a console which opens a window. How do I write to this console, using values that I am getting from controls on the form? For example such as text fields?

To access the console under windows, you have to link your program as a console-application. In Visual C++ you can configure this in the Project Settings under Configuration Properties/Linker/System/Subsystem = Console.

Linking your application as a concole-application does not mean you can't open a window. It just means a) that your process will always have a console window and b) that eg cmd.exe will execute it synchronously (=wait for it to finish before continuing the script/showing the prompt again).

Then you can access the console the usual way: using std::cout , printf etc.

AFAIK there's no (good and easy) way to get access to the console an application was started from, if the application was linked as a windowed-application. (IIRC you can however allocate a new console, but I think that's not what you want).

EDIT: If you want to print some messages to the console, even if output has been redirected, I suggest you use std::cerr to print to the "error output". The "error output" defaults to the console as well, but it's a different stream than "stdout", and it's normally not redirected. It can be redirected, but I think it's a good thing to give users that option, and not work around any redirecting by printing directly to the console.

EDIT2: When I need a "dual mode" application, ie one that can run with a GUI or in a command prompt, I use a console-application, and call FreeConsole() to get rid of the console window if the GUI version is selected via the commandline arguments (eg by not passing any arguments). That way to console will still pop up briefly if the application is started in GUI mode (eg by double-clicking in explorer), but it's immediately closed so it doesn't clutter the screen while the GUI is being used.

A windows console application by default has stdout connected to the console. If not (eg i/o was redirected by the shell), you can open the special filename "CONOUT$" .

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