|
MFC CRichEditCtrl实现不同行不同颜色
1.首先在添加在资源视图中添加CRichEditCtrl控件,并关联变量:
注意将属性Multiline和Read Only设为True:
2.初始化控件
在BOOL CRichEditTestApp::InitInstance()函数中添加:
- ...
- if (!AfxInitRichEdit2())
- {
- return FALSE;
- }
- ...
复制代码 3. 设置字体大小颜色
- int CRichEditTestDlg::GetNumVisibleLines(CRichEditCtrl* pCtrl)
- {
- CRect rect;
- long nFirstChar, nLastChar;
- long nFirstLine, nLastLine;
- // Get client rect of rich edit control
- pCtrl->GetClientRect(rect);
- // Get character index close to upper left corner
- nFirstChar = pCtrl->CharFromPos(CPoint(0, 0));
- // Get character index close to lower right corner
- nLastChar = pCtrl->CharFromPos(CPoint(rect.right, rect.bottom));
- if (nLastChar < 0)
- {
- nLastChar = pCtrl->GetTextLength();
- }
- // Convert to lines
- nFirstLine = pCtrl->LineFromChar(nFirstChar);
- nLastLine = pCtrl->LineFromChar(nLastChar);
- return (nLastLine - nFirstLine);
- }
- int CRichEditTestDlg::AppendToLogAndScroll(const CString& csMsg, COLORREF color, int iFontSize)
- {
- long nVisible = 0;
- long nInsertionPoint = 0;
- CHARFORMAT cf;
- m_richEdit.GetSelectionCharFormat(cf);
- // Initialize character format structure
- cf.cbSize = sizeof(CHARFORMAT);
- //static int iHeight = 1000;
- cf.dwMask |= CFM_BOLD;
- cf.dwEffects |= CFE_BOLD;//设置粗体,取消用cf.dwEffects&=~CFE_BOLD;
- cf.dwEffects &= ~CFE_AUTOCOLOR;
- cf.dwMask |= CFM_COLOR;
- cf.crTextColor = color;
- cf.dwMask |= CFM_SIZE;
- cf.yHeight = iFontSize;//设置高度
- cf.dwMask |= CFM_FACE;
- _tcscpy_s(cf.szFaceName, _T("微软雅黑"));//设置字体
- // Set insertion point to end of text
- nInsertionPoint = m_richEdit.GetWindowTextLength();
- m_richEdit.SetSel(nInsertionPoint, -1);
- // Set the character format
- m_richEdit.SetSelectionCharFormat(cf);
- // Replace selection. Because we have nothing
- // selected, this will simply insert
- // the string at the current caret position.
- m_richEdit.ReplaceSel(csMsg);
- // Get number of currently visible lines or maximum number of visible lines
- // (We must call GetNumVisibleLines() before the first call to LineScroll()!)
- nVisible = GetNumVisibleLines(&m_richEdit);
- // Now this is the fix of CRichEditCtrl's abnormal behaviour when used
- // in an application not based on dialogs. Checking the focus prevents
- // us from scrolling when the CRichEditCtrl does so automatically,
- // even though ES_AUTOxSCROLL style is NOT set.
- if (&m_richEdit != m_richEdit.GetFocus())
- {
- m_richEdit.LineScroll(INT_MAX);
- m_richEdit.LineScroll(1 - nVisible);
- }
- return 0;
- }
复制代码 4.使用示例:
- void CRichEditTestDlg::OnBnClickedTest()
- {
- CString strPerRet;
- strPerRet.Format(_T("红色行\n"));
- AppendToLogAndScroll(strPerRet, RGB(255, 0, 0), 300);
- strPerRet.Format(_T("绿色行\n"));
- AppendToLogAndScroll(strPerRet, RGB(0, 255, 0), 300);
- strPerRet.Format(_T("蓝色行\n"));
- AppendToLogAndScroll(strPerRet, RGB(0, 0, 255), 300);
- }
复制代码 5.效果图
|
|