views:

463

answers:

3

Hello,

I have a simple Win32 GUI app which has an edit control in the main window. If I write:

printf("Hello world!\n");

I would like the text to appear in that control instead of the console. How to?

Update: The app is just simple window with edit control and I can compile it with or without displaying the console (gcc -mwindows). Sometimes I call an external function, which might printf() something - and I would like to catch that something and display it in the edit control. So far, SetStdHandle() seems to be closest to what I try to achieve but I cannot get it to work, yet...


Update 2: Please, can someone tell me why this is not working and how to fix it?

HANDLE hRead, hWrite;
CreatePipe(&hRead, &hWrite, NULL, 0);

SetStdHandle(STD_OUTPUT_HANDLE, hWrite);

printf("Hello world!\n");

CloseHandle(hWrite); // Why is this needed?

DWORD dwRead;
BOOL bSuccess;
CHAR chBuf[4096];
bSuccess = ReadFile(hRead, chBuf, 4096, &dwRead, NULL); // This reads nothing :(

Also, it still prints "Hello world" to the console, I expected it not to..?

+1  A: 

You can do that in Windows by redirecting stdout when you create the process. You do so by setting flags and setting some handles in the STARTUPINFO structure passed to CreateProcess. See this example on MSDN for detail on how to set this up.

Once you have that setup can use ReadFile to read from the redirected stdout of the console process then send it to the edit control.

shf301
But I don't start any new processes. It's the same thread. Maybe I don't understand what you meant but the app is already started...
Tero Jokinen
+2  A: 

Check out the API call SetStdHandle. Once the stdout is redirected to your stream, read from it and send the text to the edit control.

[Edit]

Take a look at using dup2. The following code seems to work.

int fds[2];
_pipe (fds, 1024, O_TEXT);
_dup2 (fds[1], 1);      // 1 is stdout
printf ("Test\r\n");
char buffer[100];
_flushall();            // Need to flush the pipe
int len = _read (fds[0], buffer, 100);
buffer[len] = 0;        // Buffer now contains "Test\r\n"
Stephen Nutt
Ok, this looks like it. But I don't quite follow: when I:SetStdHandle(STD_OUTPUT_HANDLE, my_output) and printf() something it still appears in the console so when I try to read my_output it's empty..?
Tero Jokinen
Ad [Edit]:Thanks a lot, this works perfectly!
Tero Jokinen
A: 

write a internal __printf function can output the text to edit control, then replace all printf fucntions with that. Thanks.

Yigang Wu