Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

winapi - 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!
");

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!
");

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..?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
");
char buffer[100];
_flushall();            // Need to flush the pipe
int len = _read (fds[0], buffer, 100);
buffer[len] = 0;        // Buffer now contains "Test
"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...