For doing this, we can make use of WM_CTLCOLOR message OnCtlColor function.
If you add a handler for the above message, Windows will draw with the brush you are creating inside this function.
Before drawing childe controls, this function will be called(for certain types. refer MSDN for more info). nCtlColor parameter will only provide the type of child control. If we have three edit box named red, green, blue, and if we need to give different back color for each item, we can differentiate the controls by getting it’s ID. we can get the child control’s ID by calling GetDlgCtrlID() function of the window pointer passed to this function. The following code decribes how to implement the same.
You can use the same technique for buttons, static control and other controls supported by this message. Full list of controls is available in MSDN.
Sample Code:
HBRUSH CSampleDialogDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = NULL; // Initialize with a NULL brush
// Execute for edit box only
if(CTLCOLOR_EDIT == nCtlColor)
{
COLORREF clrBack = RGB(0,0,0);
int nCtrlID = pWnd->GetDlgCtrlID(); // Get the control ID
if(IDC_EDIT_RED == nCtrlID) // if edit blue clrBack = RGB(0xFF,0,0); // Red back color else if(IDC_EDIT_GRN == nCtrlID) // if edit green clrBack = RGB(0,0xFF,0); // Green back color else if(IDC_EDIT_BLUE == nCtrlID) // if edit blue clrBack = RGB(0,0,0xFF); // blue back color hbr = CreateSolidBrush(clrBack); // create brush with selected color
pDC->SetBkMode(TRANSPARENT); // little more tweak make the draw transparant
}
else // default brush
{
hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}
return hbr;
}