
WOWTO: console stdout/printf and GUI-based MFC application
<snip>
Quote:
> I don't know if you can have an app that is both a console app and a GUI
> app. (I actually wanted to do this myself once, and I gave up.)
You can, but you have more work to do. In order to properly
reuse the console window it's launched from, you need to
make a _console_ app.
Quote:
> One solution: have a console app that checks the command line and prints
out
> as above in the "-V" case. If "-V" is not present launch the separate GUI
> app. In other words, make a stub console app as a front end for your GUI
> app.
That's the easiest way to do it if you already have a GUI
app. The stub itself actually only has to launch the GUI,
in the appropriate way.
The problem is that you need to control how CreateProcess
is called on the GUI app to override default behavior and
give it access to the original console. By default, GUI apps
are launched _detached_, and console apps are launched
_attached_. By the time the app is launched, the decision
has been made.
From MSDN: Platform SDK: DLLs, Processes, and Threads
"Creation of a Console...
A GUI or console process can use the CreateProcess function
to create a new console process and specify a flag to tell the
system to create a new console...
GUI processes are not attached to any console when they
are created."
This means it has _no access_ to the console of the command
processor.
"A console process is not attached to a console if the
DETACHED_PROCESS flag was specified in a call to
CreateProcess when the process was created."
Which is _not_ specified by the command processor, so
the console app is attached to the parent's console.
It's just a matter of default behavior. Console apps can
create windows, and GUI apps can allocate consoles.