Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Console output from MFC dialog based app

1,818 views
Skip to first unread message

Ajay Shinde

unread,
Apr 18, 2008, 8:59:00 AM4/18/08
to
Dear All,

I have developed a MFC dialog based application. Now when I execute this app
from command prompt, I need to write some text back to console.
In console application we achieve this using functions like printf(),
puts(), etc.

Please let me know how do I achieve same in dialog based application since
printf() and other functions are not working here.

Thanks,
Ajay

AliR (VC++ MVP)

unread,
Apr 18, 2008, 10:29:48 AM4/18/08
to
You can't write to the same console window that you were ran from, but you
can create a console window and write to that.

Take a look at AllocConsole, ReadConsole, and WriteConsole.

Here is an example:
http://www.codeproject.com/KB/cpp/ConsoleAdapter.aspx


AliR.

"Ajay Shinde" <AjayS...@discussions.microsoft.com> wrote in message
news:45748FA7-EEB4-4CFB...@microsoft.com...

David Lowndes

unread,
Apr 18, 2008, 10:42:47 AM4/18/08
to

Under XP (and presumably later OS's) you can use AttachConsole like
this:

AttachConsole( ATTACH_PARENT_PROCESS );

int hCrt;
FILE *hf;

hCrt = _open_osfhandle( (intptr_t)
GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT );
hf = _fdopen( hCrt, "w" );
*stdout = *hf;
int i = setvbuf( stdout, NULL, _IONBF, 0 );

SetConsoleCtrlHandler( HandlerRoutine, true );

printf( "Hello World\n" );

Under other OS's I'm not aware of how you can do it other than to
cheat by having 2 separate programs - a console one with a .com
extension and a GUI one with a .exe extension. The .com starts first
and can then conditionally run the .exe version.

Dave

Joseph M. Newcomer

unread,
Apr 20, 2008, 1:47:10 PM4/20/08
to
A more important question is "why do you think you need to write to a console?" For
example, for debug tracing, the TRACE macro works exceedingly well, and if you need
something that will be in the final product, something like my Logging ListBox is a better
choice. Generally, although it is possible to do so, it should generally be considered
bad practice to do so.

So instead of asking how to do something that isn't very good practice, why not ask a
question based on what you are trying to accomplish?
joe

On Fri, 18 Apr 2008 05:59:00 -0700, Ajay Shinde <AjayS...@discussions.microsoft.com>
wrote:

Joseph M. Newcomer [MVP]
email: newc...@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm

Ajay Shinde

unread,
Apr 22, 2008, 3:23:00 AM4/22/08
to
Thanks AliR for your response.
Solution provided by David solved the issue.

Ajay Shinde

unread,
Apr 22, 2008, 3:22:01 AM4/22/08
to
Thanks a ton David.
It worked.
0 new messages