There are two methods. First, you can specify the color of the control in the parent class, or useMFC4.0 new message
Reflection specifies the color in the control class. When the control needs to be re-colored, the Work box calls the parent window (
Usually dialog box)CWnd: OnCrtlColor, You can reset this function in the parent window class and specify the control
New painting attributes of a widget. For example, the following code changes the text color of all edit controls in the dialog to red
Color:
HBRUSH CAboutDig: OnCtlColor (CDC * pDCM, CWnd * pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog: OnCtlColor (pDC, pWnd, nCtlColor)
// Draw red text for all edit controls.
If (nCtlColor = CTLCOLOR_EDIT)
PDC-> SetTextColor (RGB (255, 0, 0 ,))
Return hbr
}
However, since each parent window must process the notification message and specify the painting attribute of each control
This method is not a fully object-oriented method. Control to process the message and specify the painting owner
More reasonable. Message reflection allows you to do this. The notification message is sent to the parent window first,
If the parent window is not processed, it is sent to the control. To create a custom color list box, the control must comply
Follow these steps.
First, useClassWizard creates a CListBox derived class and adds the following
Data member.
Class CMyListBox publilc CListBox
{
...
Private
COLORREF m_clrFor // foreground color
COLORREF m_clrBack // background color
Cbrush m_brush // background brush
...
}
Second, in the class constructor, the initialization data.
CMyListBox: CMyListBox ()
{
// Initialize data members.
M_clrFore = RGB (255,255, 0) // yellow text
M_clrBack = RGB (0, 0,255) // blue background
M_brush. CreateSolidBrush (m _ clrBack)
}
Finally, useClassWizard processes the reflected WM_CTLCOLOR (= WM_CTLCOLOR) message and specifies
New painting attributes.
HBRUSH CMyListBox: CtlColor (CDC * pDC, UINT nCtlColor)
{
PDC-> SetTextColor (m_clrFore)
PDC-> SetBkColor (m_clrBack)
Return (HBRUSH) m_brush.GetSafeHandle ()
}
Now, the control can decide how to paint it by yourself, and it has nothing to do with the parent window.