Changing the Color of Controls in Dialogs

Date: 28 January 1997
Author: Mario Zimmermann
Updated by Christopher Kohlhoff with input by Mark Caroli.

To change the color of controls (i.e. TEdit, TCheckBox, TRadioButton...) in dialogs it is necessary to override EvCtlColor in your dialog class.

The following code example changes the text color of an TEdit control to light red on a white background:

DEFINE_RESPONSE_TABLE1(TMyDialog, TDialog)
  EV_WM_CTLCOLOR,
END_RESPONSE_TABLE;

HBRUSH TMyDialog::EvCtlColor (HDC hDC, HWND hWndChild, UINT ctlType)
{
    static HBRUSH greyBrush = (HBRUSH) GetStockObject (GRAY_BRUSH);

    // Set the colours for a particular edit window.
    //
    if ( hWndChild == MyEdit->HWindow )
    {
        TDC DC (hDC);

        // Set the text colour used by the edit control.
        //
        DC.SetTextColor (TColor::LtRed);

        // Set the text background mode to transparent to
        // show our alternative colour background.
        //
        DC.SetBkMode (TRANSPARENT);

        // The brush returned by the EvCtlColor function
        // is used as the background colour of the control.
        //
        return ( greyBrush );
    }

    // Change the background colour for all listboxes.
    //
    if ( ctlType == CTLCOLOR_LISTBOX )
      return ( greyBrush );

    return ( TDialog::EvCtlColor (hDC, hWndChild, ctlType) );
}

Note: Win32 replaced the WM_CTLCOLOR message with separate WM_CTLCOLORXXX messages for the individual control types. To help you write portable code, OWL converts these messages back into the WM_CTLCOLOR message so that you can handle it all in the function EvCtlColor.