将标准输出重定向到编辑控件 (Win32) [英] Redirect stdout to an edit control (Win32)

查看:67
本文介绍了将标准输出重定向到编辑控件 (Win32)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Win32 GUI 应用程序,它在主窗口中有一个编辑控件.如果我写:

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?

更新:该应用程序只是带有编辑控件的简单窗口,我可以在显示或不显示控制台 (gcc -mwindows) 的情况下对其进行编译.有时我会调用一个外部函数,它可能会 printf() 一些东西 - 我想抓住那个东西并将它显示在编辑控件中.到目前为止, SetStdHandle() 似乎最接近我试图实现的目标,但我无法让它工作,但是......

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

更新 2:请有人告诉我为什么这不起作用以及如何解决它?

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 :(

此外,它仍然向控制台打印Hello world",我预计它不会......?

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

推荐答案

查看 API 调用 SetStdHandle.将标准输出重定向到您的流后,从中读取并将文本发送到编辑控件.

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.

看看如何使用 dup2.以下代码似乎有效.

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"

这篇关于将标准输出重定向到编辑控件 (Win32)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆