在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 靜態控件
[程序實現]
假設你已有了名為My的對話框工程.你有了一個STATIC的控件,ID為IDC_STATIC1.
HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// 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;
}
如果要指定某個特定控件可以這樣寫:ID為IDC_STATIC1
if (pWnd->GetDlgCtrlID()==IDC_STATIC1)
{
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;
【注】
BLACK_BRUSH:黑色
WHITE_BRUSH:白色
GRAY_BRUSH:灰色
NULL_BRUSH:透明
HOLLOW_BRUSH :透明
1.為對話框類添加WM_CTLCOLOR的響應函數afx_msg HBRUSH OnCtlColor(CDC*pDC,CWnd*pWnd,UINT nCtlColor){...}
2.定義一個m_brush(CBrush類型)的成員變量和一個m_font(CFont類型)成員變量,在構造函數中初始化,例如:m_brush.CreateSolidBrush(RGB(0,0,255));m_font.CreatePointFont(200,"華文行楷");
3.改變背景顏色和文本顏色和字體:在OnCtlColor()添加代碼:
if(pWnd->GetDlgCtrlID()==IDC_LINE_STYLE/*控件ID*/)
{
pDC->SetTextColor(RGB(255,0,0));
pDC->SetBkMode(TRANSPARENT);//設置文本背景色為透明
pDC->SelectObject(&m_font);//設置字體
return m_brush;//設置控件背景顏色
}
//對于按鈕來說上面的方法無效