2012-12-01 4 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()을 호출하여 텍스트 영역의 끝에 "삽입"하면이 작업을 완전히 수행 할 수 있습니다. "N \) + 텍스트?"L " `m_txtLog.ReplaceSel ((txtLen <1 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

:

나는 당신의 방법은 다음과 같이 보일한다고 생각합니다); ' 예상대로 새 줄을 추가합니다. 감사! – RectangleEquals

+0

@RectangleEquals 그것을 듣기 좋습니다! : D –

+1

나는 마스크가 cf.dwMask = CFM_BOLD |이어야한다고 생각한다. CFM_ITALIC | CFM_COLOR; 그렇지 않으면 굵은 체 또는 기울임 체를 켜면 끌 수 없습니다. – dougnorton

관련 문제