重载OnCtlColor函数,这个是必须的 。
设置控件的背景颜色:
第一:
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);//在头文件中声明
在主文件中
第二:BEGIN_MESSAGE_MAP(COk1Dlg, CDialog)
//{{AFX_MSG_MAP(COk1Dlg)
。。。
ON_WM_CTLCOLOR() //要加这句
。。。。。。。
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
第三:加这个函数
HBRUSH CTesDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
switch (nCtlColor)
{
case CTLCOLOR_STATIC: //静态文本
{
pDC->SetBkMode(TRANSPARENT);
HBRUSH B = CreateSolidBrush(RGB(255, 0, 0)); //控件背景颜色
pDC->SetTextColor(RGB(255,0,0)); //控件中的文字的颜色
return (HBRUSH) B;
}
break;
case CTLCOLOR_LISTBOX://列表框
{
pDC->SetBkMode(TRANSPARENT);
HBRUSH B = CreateSolidBrush(RGB(0, 255, 0));
pDC->SetTextColor(RGB(255,0,0));
return (HBRUSH) B;
}
break;
case CTLCOLOR_DLG : //对话框
{
pDC->SetBkMode(TRANSPARENT);
HBRUSH B = CreateSolidBrush(RGB(0, 0, 255));
pDC->SetTextColor(RGB(255,0,0));
return (HBRUSH) B;
}
break;
case CTLCOLOR_EDIT : //文本编辑框
{
pDC->SetBkMode(TRANSPARENT);
HBRUSH B = CreateSolidBrush(RGB(60, 160, 60));
pDC->SetTextColor(RGB(255,0,0));
return (HBRUSH) B;
}
break;
default:
break;
return hbr;
}
}
控件参考:
#define CTLCOLOR_MSGBOX 0
#define CTLCOLOR_EDIT 1
#define CTLCOLOR_LISTBOX 2
#define CTLCOLOR_BTN 3
#define CTLCOLOR_DLG 4
#define CTLCOLOR_SCROLLBAR 5
#define CTLCOLOR_STATIC 6
#define CTLCOLOR_MAX 7
#define COLOR_SCROLLBAR 0
#define COLOR_BACKGROUND 1
#define COLOR_ACTIVECAPTION 2
#define COLOR_INACTIVECAPTION 3
#define COLOR_MENU 4
#define COLOR_WINDOW 5
#define COLOR_WINDOWFRAME 6
#define COLOR_MENUTEXT 7
#define COLOR_WINDOWTEXT 8
#define COLOR_CAPTIONTEXT 9
#define COLOR_ACTIVEBORDER 10
#define COLOR_INACTIVEBORDER 11
#define COLOR_APPWORKSPACE 12
#define COLOR_HIGHLIGHT 13
#define COLOR_HIGHLIGHTTEXT 14
#define COLOR_BTNFACE 15
#define COLOR_BTNSHADOW 16
#define COLOR_GRAYTEXT 17
#define COLOR_BTNTEXT 18
#define COLOR_INACTIVECAPTIONTEXT 19
#define COLOR_BTNHIGHLIGHT 20
#if(WINVER >= 0x0400)
#define COLOR_3DDKSHADOW 21
#define COLOR_3DLIGHT 22
#define COLOR_INFOTEXT 23
#define COLOR_INFOBK 24
#endif /* WINVER >= 0x0400 */
#if(WINVER >= 0x0500)
#define COLOR_HOTLIGHT 26
#define COLOR_GRADIENTACTIVECAPTION 27
#define COLOR_GRADIENTINACTIVECAPTION 28
#if(WINVER >= 0x0501)
#define COLOR_MENUHILIGHT 29
#define COLOR_MENUBAR 30
#endif /* WINVER >= 0x0501 */
#endif /* WINVER >= 0x0500 */
#if(WINVER >= 0x0400)
#define COLOR_DESKTOP COLOR_BACKGROUND
#define COLOR_3DFACE COLOR_BTNFACE
#define COLOR_3DSHADOW COLOR_BTNSHADOW
#define COLOR_3DHIGHLIGHT COLOR_BTNHIGHLIGHT
#define COLOR_3DHILIGHT COLOR_BTNHIGHLIGHT
#define COLOR_BTNHILIGHT COLOR_BTNHIGHLIGHT
另外,有的控件不在上面定义之中,这时要改变就需要获得控件的ID来改变,具体如下(上面的也可以用下面的这种方法来实现)
首先还是要重载OnctlColor函数
然后
if(pWnd->GetDlgCtrlID()==YourID//你想改变的控件Id)
{
pDC->SetTextColor(RGB(……));
SetBKMode(TRANSPARENT);
hbr=m_brush;//这里把画刷改成你自己的
}
return hbr;
这样就可以实现了 ,很简单吧!