MFC: CEdit color change

Guys, can someone give me a brief info on how to change the background color of the CEdit control at runtime? I want to change the background to red if the field is zero and normal white otherwise.

+4
source share
2 answers

You cannot do this with a simple CEdit, you need to override a few bits.

Add your own ON_WM_CTLCOLOR_REFLECT handler, and then return the color CBrush to the handler:

(roughly speaking, you need to put the usual resource management there, rememebr, to remove the 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); } } 
+6
source

This can also be done without CEdit output:

  • Add ON_WM_CTLCOLOR() to your BEGIN_MESSAGE_MAP() code block.
  • Add OnCltColor() to your dialog class:

     afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); 
  • OnCtlColor() like this:

     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); } 
+3
source

All Articles