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 e.g. 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, i.e. 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 (e.g. by not passing any arguments). That way to console will still pop up briefly if the application is started in GUI mode (e.g. 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 (e.g. i/o was redirected by the shell), you can open the special filename "CONOUT$"
.
精彩评论