Your example code reads the old text out of the dialog with a call to GetTextRange()
. This does not include any rich formatting so, when the text is put back in place, it is not formatted. You can completely forgo this by "inserting" at the end of the text area by setting the cursor to the end without any selection and calling ReplaceSel()
.
I think your method should look something like this:
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 = CFM_BOLD | CFM_ITALIC | CFM_COLOR;
cf.dwEffects = (bold ? CFE_BOLD : 0) | (italic ? CFE_ITALIC : 0);
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);
}