2012-12-01 92 views
1

我有一個MFC項目中的CRichEditCtrl,我用它作爲報告日誌。 根據給定的情況,我需要將不同顏色的文本添加到控件中(例如標準通知的藍線,錯誤的紅線等)。 我來非常接近得到這個工作,但它仍然行爲異常:

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... 

那麼如何才能解決這個到以前所有的文本和格式不變化,同時添加一行新的彩色文字?

回答

4

您的示例代碼通過調用GetTextRange()來讀取對話框中的舊文本。這不包括任何豐富的格式,所以當文本放回原處時,它不會被格式化。您可以通過將光標設置到最後而不進行任何選擇,並在文本區域的末尾「插入」,然後調用ReplaceSel()完全放棄這一點。

我覺得你的方法應該是這個樣子? 「:L」

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); 
} 
+0

更改相應的行 'm_txtLog.ReplaceSel((txtLen RectangleEquals

+0

@RectangleEquals很高興聽到它! :D –

+1

我認爲掩碼應該是cf.dwMask = CFM_BOLD | CFM_ITALIC | CFM_COLOR;否則一旦你打開粗體或斜體,你不能關閉它們。 – dougnorton