在MFC类库提供了CWnd::OnCtlColor函数,在子窗口被重画时将调用该成员函数,因此可以重载WM_CTLCOLOR消息的响应函数。
函数的原型:afx_msg HBRUSH OnCtlColor(CDC *pDC,CWnd *pWnd,UINT nCtlColor);
参数nCtlColor用于指定控件的类型如下:
CTLCOLOR_BTN 按钮控件
CTLCOLOR_DLG 对话框
CTLCOLOR_EDIT 编辑框
CTLCOLOR_LISTBOX 列表控件
CTLCOLOR_MSGBOX 消息控件
CTLCOLOR_SCROLLBAR 滚动条控件
CTLCOLOR_STATIC 静态控件
假设在MFC对话框工程中,有一个 STATIC 控件,ID为IDC_STATIC_INFO。
// TODO: Change any attributes of the DC here
if (nCtlColor == CTLCOLOR_STATIC)
{
pDC-> SetTextColor(RGB(255,0,0)); //字体颜色
pDC-> SetBkColor(RGB(0, 0, 255)); //字体背景色
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
注:以上代码会修改所有STATIC控件的字体颜色和字体背景色。
// TODO: Change any attributes of the DC here
if (pWnd-> GetDlgCtrlID() == IDC_STATIC_INFO)
{
pDC-> SetTextColor(RGB(255,0,0)); //字体颜色
pDC-> SetBkColor(RGB(0, 0, 255)); //字体背景色
return (HBRUSH)::GetStockObject(BLACK_BRUSH); //设置背景色
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
注:以上代码会修改 IDC_STATIC_INFO 控件的字体颜色、字体背景色和控件背景色。
附注:
1、GetStockObject能指定的颜色有:
BLACK_BRUSH:黑色
WHITE_BRUSH:白色
GRAY_BRUSH:灰色
NULL_BRUSH:透明
HOLLOW_BRUSH:透明
2、HBRUSH hbr = CreateSolidBrush(RGB(255,255,255));
3、当Edit被设定为只读时,编辑框被当成STATIC看待,即 nCtlColor == CTLCOLOR_STATIC