Changing the Background Color of Edit Controls
Click here for larger image
If you need to change the background color of CEdit controls on your dialog, it is very simple.
The following example will change the background colour of specific CEdit controls and each can be a different colour ! I have chosen Blue and Red backgrounds with White text for this example.
In your CTestDlg header file, declare member variables from CBrush and COLORREF:
class CTestDlg : public CDialog
{
protected:
CBrush m_redbrush,m_bluebrush;
COLORREF m_redcolor,m_bluecolor,m_textcolor;
};
Then, add these lines in the OnInitDialog function:
BOOL CTestDlg::OnInitDialog()
{
m_redcolor=RGB(255,0,0); // red
m_bluecolor=RGB(0,0,255); // blue
m_textcolor=RGB(255,255,255); // white text
m_redbrush.CreateSolidBrush(m_redcolor); // red background
m_bluebrush.CreateSolidBrush(m_bluecolor); // blue background
}
Finally do this on the ID_CTLCOLOR handle:
HBRUSH CTestDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr;
switch (nCtlColor)
{
case CTLCOLOR_EDIT:
case CTLCOLOR_MSGBOX:
switch (pWnd->GetDlgCtrlID())
{
case IDC_MYCONTROLNAME1: // first CEdit control ID
// put your own CONTROL ID here
pDC->SetBkColor(bluecolor); // change the background color
pDC->SetTextColor(textcolor); // change the text color
hbr = (HBRUSH) m_bluebrush; // apply the brush
break;
case IDC_MYCONTROLNAME2: // second CEdit control ID
// put your own CONTROL ID here
pDC->SetBkColor(redcolor); // change the background color
pDC->SetTextColor(textcolor); // change the text color
hbr = (HBRUSH) m_redbrush; // apply the brush
break;
// otherwise do default handling of OnCtlColor
default:
hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
break;
}
break;
// otherwise do default handling of OnCtlColor
default:
hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
}
return hbr; // return brush
}