gpt4 book ai didi

c++ - mfc richedit2格式化

转载 作者:行者123 更新时间:2023-11-27 23:19:26 25 4
gpt4 key购买 nike

我正在尝试使用丰富的编辑控件在屏幕上输出一些文本:

星期一 按 1。
你的日子是星期一
星期二按 2。

我真的找不到任何简单的例子来说明如何做到这一点。我所能解决的只是设置窗口文本(setWindowText),但其他一切都在逃避我。有什么简短的例子吗?

最佳答案

尽管有评论,但我还是要回答您提出的关于如何在 Rich Edit 控件中设置数据格式的问题。几年前,我不得不这样做,并提出了一些我可以像 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,并将选择设置为刚好在结尾之后。

关于c++ - mfc richedit2格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14340367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com