Redirect stdout to an edit control (Win32)
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 comp开发者_JS百科ile 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..?
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"
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.
Write a internal __printf function can output the text to edit control, then replace all printf functions with that.
精彩评论