I have a CRichEditCtrl in an MFC project, which I use as a report log.
Depending on the given situation, I need to append different colored text to the control (ie. a blue line for standard notifications, a red line for errors, etc).
I've come pretty close to getting this to work, but it still behaves strangely:
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);
}
At best, the end result is that the newly appended line is appropriately colored but all of the previous text turns black. On top of that, for each appended line of text, the starting selection seems to increase by 1. For example:
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...
So how can I fix this to where all the previous text and formatting remain as-is, while appending a new line of colored text?