Rec*_*als 2 c++ mfc text colors cricheditctrl
我在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);
}
Run Code Online (Sandbox Code Playgroud)
充其量,最终结果是新添加的行被适当地着色,但是所有先前的文本变为黑色。最重要的是,对于每行追加的文本,开始的选择似乎都增加了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...
Run Code Online (Sandbox Code Playgroud)
那么,如何在附加新的彩色文本行的同时,将其固定为所有先前的文本和格式保持不变的位置?
您的示例代码通过调用来从对话框中读取旧文本GetTextRange()。这不包括任何格式丰富的格式,因此,当文本放回原位时,不会对其进行格式化。您可以通过将光标设置在文本区域的末尾而无需任何选择并调用来完全放弃此操作ReplaceSel()。
我认为您的方法应如下所示:
void CMFCApplication2Dlg::InsertText(CString text, COLORREF color, bool bold, bool italic)
{
CHARFORMAT cf = {0};
int txtLen = m_txtLog.GetTextLength();
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.SetSel(txtLen, -1); // Set the cursor to the end of the text area and deselect everything.
m_txtLog.ReplaceSel(text); // Inserts when nothing is selected.
// Apply formating to the just inserted text.
m_txtLog.SetSel(txtLen, m_txtLog.GetTextLength());
m_txtLog.SetSelectionCharFormat(cf);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4518 次 |
| 最近记录: |