我在 MFC 项目中有一个 CRichEditCtrl,我将其用作报告日志。根据给定的情况,我需要将不同颜色的文本附加到控件(即标准通知的蓝线,错误的红线等)。我已经非常接近让它工作了,但它仍然表现得很奇怪:
void CMyDlg::InsertText(CString text, COLORREF color, bool bold, bool italic)
{
CHARFORMAT cf = {0};
CString txt;
int txtLen = m_txtLog.GetTextLength();
m_txtLog.GetTextRange(0, txtLen, txt);
cf.cbSize = sizeof(cf);
cf.dwMask = (bold ? CFM_BOLD : 0) | (italic ? CFM_ITALIC : 0) | CFM_COLOR;
cf.dwEffects = (bold ? CFE_BOLD : 0) | (italic ? CFE_ITALIC : 0) |~CFE_AUTOCOLOR;
cf.crTextColor = color;
m_txtLog.SetWindowText(txt + (txt.GetLength() > 0 ? "\n" : "") + text);
m_txtLog.SetSel(txtLen, m_txtLog.GetTextLength());
m_txtLog.SetSelectionCharFormat(cf);
}
充其量,最终结果是新附加的行被适当地着色,但所有先前的文本都变成黑色。最重要的是,对于每个附加的文本行,起始选择似乎增加了 1。例如:
Call #1:
- [RED]This is the first line[/RED]
Call #2:
- [BLACK]This is the first line[/BLACK]
- [GREEN]This is the second line[/GREEN]
Call #3:
- [BLACK]This is the first line[/BLACK]
- [BLACK]This is the second line[/BLACK]
- [BLUE]This is the third line[/BLUE]
Call #4:
- [BLACK]This is the first line[/BLACK]
- [BLACK]This is the second line[/BLACK]
- [BLACK]This is the third line[/BLACK]
- [BLACK]T[/BLACK][YELLOW]his is the fourth line[/YELLOW]
Call #5:
- [BLACK]This is the first line[/BLACK]
- [BLACK]This is the second line[/BLACK]
- [BLACK]This is the third line[/BLACK]
- [BLACK]This is the fourth line[/BLACK]
- [BLACK]Th[/BLACK][ORANGE]is is the fifth line[/ORANGE]
etc...
那么我该如何解决这个问题,让所有以前的文本和格式保持原样,同时附加一行新的彩色文本呢?