2

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

Community
  • 1
  • 1
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164

1 Answers1

2

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));
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
  • Thanks. I get you. How do we ensure that in `OnKillFocus` it reverts back to the "default" background colour? IE: if they are using WindowsBlinds ... the background might not be white. – Andrew Truckle Oct 29 '18 at 15:32
  • 1
    I guess I should have put `GetSysColor(COLOR_WINDOW)` for default color in `OnKillFocus` – Barmak Shemirani Oct 29 '18 at 15:38