HBRUSH CConnectDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
// This function sets the text color HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); // Set them navy
if (CTLCOLOR_STATIC == nCtlColor)
{
int ctrlID = pWnd->GetDlgCtrlID();
pDC->SetTextColor (RGB(0, 0, 192));
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
{
// This function sets the text color HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); // Set them navy
if (CTLCOLOR_STATIC == nCtlColor)
{
int ctrlID = pWnd->GetDlgCtrlID();
pDC->SetTextColor (RGB(0, 0, 192));
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
根据pWnd判断是不是要修改的控件窗口
把事先定义好的Brush的句柄作为返回值返回。
HBRUSH CDlgAddUser::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
int nCtrId = pWnd->GetDlgCtrlID();
if(nCtrId == IDC_TEXT)
{
pDC->SetBkMode(TRANSPARENT);
return (HBRUSH)GetStockObject(WHITE_BRUSH);
} // TODO: Return a different brush if the default is not desired
return hbr;
}
[email protected]
老兄,看了代码后,能不能多加一点分
唉
发到[email protected]
有两种方法。其一,可以在父类中指定控件的颜色,或者利用MFC4.0新的消息反射在控件类中指定颜色。 当控件需要重新着色时,工作框调用父窗口(通常是对话框)的CWnd: : OnCrtlColor,可以在父窗口类中重置该函数并指定控件的新的绘画属性。例如,下述代码将对话中的所有编辑控件文本颜色改为红色:
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
}
然而,由于每个父窗口必须处理通知消息并指定每个控件的绘画属性,所以,这种方法不是完全的面向对象的方法。控件处理该消息并指定绘画属性更合情合理。消息反射允许用户这样做。通知消息首先发送给父窗口,如果父窗口没有处理则发送给控件。创建一个定制彩色列表框控件必须遵循下述步骤。
首先,使用ClassWizard 创建一个CListBox 的派生类并为该类添加下述数据成员。
class CMyListBox publilc CListBox
{
…
private
COLORREF m_clrFor // foreground color
COLORREF m_clrBack //background color
Cbrush m_brush //background brush
…
}
其次,在类的构造函数中,初始化数据中。
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 )
}
最后,使用ClassWizard处理反射的WM_CTLCOLOR(=WM_CTLCOLOR)消息并指定新的绘画属性。
HBRUSH CMyListBox : : CtlColor (CDC* pDC, UINT nCtlColor )
{
pDC—>SetTextColor (m_clrFore)
pDC—>SetBkColor (m_clrBack)
return (HBRUSH) m_brush.GetSafeHandle ()
}
现在,控件可以自己决定如何绘画,与父窗口无关。