Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 796
Konrad Avatar asked Oct 20 '08 10:10

Konrad


People also ask

How do I change the background color on MFC?

1) Added "CBrush m_brush" to the header public. 2) Added "m_brush. CreateSolidBrush(RGB(255, 0, 0))" on init. 3) Added OnCtlColor in Dlg.

How do I change the color of my static text in MFC?

MFC provides a CWnd::OnCtlColor function for that. Actually this function handles the WM_CTLCOLOR messages of the window. The framework calls this member function when a child control is about to be drawn. If you want to do it in the Win32 application just handle the message WM_CTLCOLORSTATIC .


2 Answers

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);
  }
}
like image 124
gbjbaanb Avatar answered Sep 22 '22 14:09

gbjbaanb


This can also be done without deriving from CEdit:

  1. Add ON_WM_CTLCOLOR() to your dialog's BEGIN_MESSAGE_MAP() code block.
  2. Add OnCltColor() to your dialog class:

    afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
    
  3. Implement OnCtlColor() like so:

    HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
    {
        if ((CTLCOLOR_EDIT == nCtlColor) &&
            (IDC_MY_EDIT == pWnd->GetDlgCtrlID()))
        {
            return m_brMyEditBk; //Create this brush in OnInitDialog() and destroy in destructor
        }
        return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
    }
    
like image 34
amolbk Avatar answered Sep 21 '22 14:09

amolbk