MFC类库提供了CWnd::OnCtlColor函数,在工作框架的子窗口被重画时将调用该成员函数.在界面处理的时候很有用处
因此可以重载WM_CTLCOLOR消息的响应函数.
【MSDN】此函数的原型:
The framework calls this member function when a child control is about to be drawn
afx_msg HBRUSH OnCtlColor(CDC *pDC,CWnd *pWnd,UINT nCtlColor);
pDC
Contains a pointer to the display context for the child window. May be temporary.
pWnd
Contains a pointer to the control asking for the color. May be temporary.
nCtlColor
Contains one of the following values, specifying the type of control:
CTLCOLOR_BTN Button control
CTLCOLOR_DLG Dialog box
CTLCOLOR_EDIT Edit control
CTLCOLOR_LISTBOX List-box control
CTLCOLOR_MSGBOX Message box
CTLCOLOR_SCROLLBAR Scroll-bar control
CTLCOLOR_STATIC Static control
参数nCtlColor用于指定控件的类型,可以是:
.CTLCOLOR_BTN 按钮控件
.CTLCOLOR_DLG 对话框
.CTLCOLOR_EDIT 编辑框
.CTLCOLOR_LISTBOX 列表控件
.CTLCOLOR_MSGBOX 消息控件
.CTLCOLOR_SCROLLBAR 滚动条控件
.CTLCOLOR_STATIC 静态控件
返回值:
OnCtlColor must return a handle to the brush that is to be used for painting the control background
使用方式一:
假设你已有了名为My的对话框工程.你有了一个STATIC的控件,ID为IDC_STATIC.
HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) {HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);// TODO: Change any attributes of the DC hereif (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 desiredreturn hbr;}
使用方式二:
如果要指定某个特定控件可以这样写
if (pWnd->GetDlgCtrlID()==IDC_STATIC) // 获取控件的ID
{
pDC->SetTextColor(RGB(255,0,0)); //设置字体颜色
pDC->SetBkMode(TRANSPARENT); //设置字体背景为透明
// TODO: Return a different brush if the default is not desired
return (HBRUSH)::GetStockObject(BLACK_BRUSH); // 设置背景色
}
else
return hbr;
【注】
WHITE_BRUSH:白色
GRAY_BRUSH:灰色
NULL_BRUSH:透明
HOLLOW_BRUSH :透明