visual-c++mfccolorscedit

MFC: Changing the colour of CEdit


Guys, can someone give me a brief run through of how to change the background colour of a CEdit control at runtime? I want to be able to change the background to red if the field is zero length and the normal white otherwise.


Solution

  • You cannot do it with a plain CEdit, you need to override a few bits.

    Implement your own ON_WM_CTLCOLOR_REFLECT handler, then return your coloured CBrush in the handler:

    (roughly, you'll need to put the usual resource management in there, rememebr to delete your brush in the destructor)

    class CColorEdit : public CEdit
    {
      ....
      CBrush   m_brBkgnd;
      afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor)
      {
        m_brBkgnd.DeleteObject();
        m_brBkgnd.CreateSolidBrush(nCtlColor);
      }
    }