Is it possible to change the background colour of

2019-07-09 05:30发布

问题:

VS2015 Dialog MFC

I have several CMFCEditBrowseCtrl implemented on my dialog with custom behavior for the browse button:

Is it possible to conditionally set the background of the edit part of the control to red at run time? And when required set the background of the edit back to the default?

Thank you.

Update I see that the control is derived from CEdit, so I am going to give this a try:

MFC: Changing the colour of CEdit

回答1:

The answer from above link is in the right direction, however it is not implemented correctly. CtlColor should return a brush handle. It also needs to set text background color with CDC::SetBkColor

class cmfc_edit : public CMFCEditBrowseCtrl
{
public:
    COLORREF bkcolor;
    CBrush brush;

    void setBrushColor(COLORREF clr)
    {
        bkcolor = clr;
        brush.DeleteObject();
        brush.CreateSolidBrush(clr);
    }

    HBRUSH CtlColor(CDC* pDC, UINT)
    {
        if (!brush.GetSafeHandle())
            return GetSysColorBrush(COLOR_WINDOW);
        pDC->SetBkColor(bkcolor);
        return brush;
    }

    //optional, change color on focus change
    void OnSetFocus(CWnd* w)
    {
        setBrushColor(RGB(255, 0, 0));
        CMFCEditBrowseCtrl::OnSetFocus(w);
    }

    void OnKillFocus(CWnd* w)
    {
        setBrushColor(RGB(255, 255, 255));
        CMFCEditBrowseCtrl::OnKillFocus(w);
    }

    DECLARE_MESSAGE_MAP()
};

BEGIN_MESSAGE_MAP(cmfc_edit, CMFCEditBrowseCtrl)
    ON_WM_CTLCOLOR_REFLECT()

    //optional
    ON_WM_SETFOCUS()
    ON_WM_KILLFOCUS()
END_MESSAGE_MAP()

usage:

mfc_edit.setBrushColor(RGB(255, 0, 0));


标签: mfc