Is it possible to change the background colour of

2019-07-09 05:04发布

VS2015 Dialog MFC

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

CMFCEditBrowseCtrl dialog

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

标签: mfc
1条回答
看我几分像从前
2楼-- · 2019-07-09 05:24

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));
查看更多
登录 后发表回答