Want to show colored box around Richedit control i

2019-08-08 14:46发布

问题:

I have an mfc application. I have some richedit controls on the dialog. I want to show a yellow colored filled frame around the controls. What is the way to do this?

I tried to create one more rich edit ctrl around the existing richedit ctrl and use SetBackgroundColor on its variable, but it colors the entire area and other richedit ctrls become invisible. Also, I want to change the surrounding color at run time. Please help me. I am stuck with this.

回答1:

There may be a better way to accomplish this, but, the following should work. If you derive your own class from CRichEditCtrl, you can leverage the WM_NCPAINT message to render the border. Something like…

void RichEdit::OnNcPaint()
    {
    CPaintDC dc(this); // device context for painting
    CRect rect;
    GetWindowRect(&rect);
    ScreenToClient(rect);

    CPen pen;
    pen.CreatePen(PS_SOLID, 10, RGB(255, 255, 0));
    dc.SelectObject(pen);
    dc.Rectangle(&rect);

    CHARFORMAT cf = { 0 };
    int txtLen = GetTextLength();

    cf.cbSize = sizeof(cf);
    cf.dwMask = CFM_ITALIC;

    SetSel(txtLen, -1); ReplaceSel("Some text"); 

    // Apply formating to the just inserted text.
    SetSel(txtLen, GetTextLength());
    SetSelectionCharFormat(cf);
    SetFocus();

    // Do not call CRichEditCtrl::OnNcPaint() for painting messages
    }

Will render the border as Yellow, and, write the corresponding text. Here’s what it will look like.