我试图使用一个富编辑控件在屏幕上输出一些文本:
周一出版社1。
Your day is **Monday**
,出版社,星期二。
我真的找不到任何简单的例子来说明如何做到这一点。我所能做的就是设置窗口文本(setWindowText),但是其他的一切都在逃避我。有什么简短的例子吗?
发布于 2013-01-15 16:37:44
尽管有这些评论,我还是要回答您提出的关于如何在Rich控件中格式化数据的问题。几年前,我不得不这样做,我想出了一些我可以把它当作IOstream来对待的东西(如果我今天就这么做的话,我可能会做一些不同的事情,但这就是生活)。
首先,代码要像IOstream那样运行,但是要写到富编辑控件:
// rich_stream.h:
#ifndef RICH_STREAM_H
#define RICH_STREAM_H
class rich_stream {
CRichEditCtrl &ctrl;
public:
rich_stream(CRichEditCtrl &ctrl_) : ctrl(ctrl_) { }
void add_text(char const *txt) {
ctrl.SetSel(-1,-1);
ctrl.ReplaceSel(txt);
}
void add_int(int val) {
CString temp;
temp.Format("%d", val);
add_text(temp);
}
void set_char_format(CHARFORMAT &fmt) {
ctrl.SetSelectionCharFormat(fmt);
}
};
inline rich_stream &operator<<(rich_stream &s, char const *t) {
s.add_text(t);
return s;
}
inline rich_stream &operator<<(rich_stream &s, CHARFORMAT &fmt) {
s.set_char_format(fmt);
return s;
}
inline CString nl() {
return CString("\n\n");
}
inline rich_stream &operator<<(rich_stream &s, CString (*f)()) {
s.add_text(f());
return s;
}
inline rich_stream &operator<<(rich_stream &s, int val) {
s.add_int(val);
return s;
}
#endif
然后,我会用这样的方法:
CHARFORMAT bold;
memset(&bold, 0, sizeof(bold));
bold.cbSize = sizeof(bold);
bold.dwMask = CFM_BOLD | CFM_FACE | CFM_SIZE;
bold.dwEffects = CFE_BOLD;
strcpy(bold.szFaceName, "Times");
bold.yHeight = 14 * 20;
CHARFORMAT normal;
memset(&normal, 0, sizeof(normal));
normal.cbSize = sizeof(normal);
normal.dwMask = CFM_BOLD | CFM_FACE | CFM_SIZE;
normal.dwEffects = 0;
strcpy(normal.szFaceName, "Times");
normal.yHeight = 14 * 20;
// ...
rich_stream txt(GetRichEditCtrl());
txt << bold << "Heading 1: " << normal << info1 << nl
<< bold << "Heading 2: " << normal << info2 << nl
<< bold << "Heading 3: " << normal << info3;
如果我今天就这样做的话,我几乎肯定会创建一个小类作为CHARFORMAT
的包装器,这样我就可以更清晰地构造格式化对象。我可能至少也会认真考虑将其实现为一个普通的iostream,它使用流缓冲区将数据插入到富编辑控件中(但当时我还不太了解流,不知道我应该这么做)。
简单地看一下,还有一些其他的事情也不完全正确-- add_text
使用SetSel(-1, -1);
。这将真正检索文本的当前长度(例如,使用GetWindowTextLength
),并在结束后将选择设置为。
发布于 2013-01-15 16:12:48
使用写字板,它也是一个RichEdit控件。它将以一种自然与您的控制兼容的方式生成您的RTF。
https://stackoverflow.com/questions/14340367
复制相似问题