在VC编程中要改变控件(诸如CView, CFrameWnd, or CWnd等)的背景色可通过处理特定的消息来实现。但如果想改变按钮的颜色,就只能使用自绘制的按钮(也可以用位图按钮,此处未做说明)而不能通过OnCtlColor()改变。 一、在一个MFC应用程序中,要改变控件的背景色可通过重载OnCtlColor()函数来实现。方法是在该函数中设置所需颜色后再返回一个画刷句柄便可重绘控件背景色。OnCtlColor()函数对于控件背景色的处理是通过捕捉相应的控件消息来实现的。常用的此类消息有:
CTLCOLOR_DLG 对话框
CTLCOLOR_EDIT 编辑框
CTLCOLOR_LISTBOX 列表框
CTLCOLOR_MSGBOX 消息框
CTLCOLOR_SCROLLBAR 滑动条
CTLCOLOR_STATIC 静态文本框、矩形等。
以下示例代码说明如何更改以上控件的背景色:
//CmyDialog.h定义
class CMyDialog : public Cdialog //派生自己的对话框类
{
……..
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CMyDialog)
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
…….
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//CmyDialog.cpp 定义
……
HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
switch (nCtlColor) {
case CTLCOLOR_EDIT:
case CTLCOLOR_MSGBOX:
case CTLCOLOR_DLG :
case CTLCOLOR_EDIT : //在此加入你想要改变背景色的控件消息
pDC->SetBkMode(TRANSPARENT);
HBRUSH B = CreateSolidBrush(COLOR); //COLOR是你想设置的颜色
return (HBRUSH) B;
default: //其他控件设置自己默认的颜色和背景刷.
return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}}
说明:1、可分别处理以上消息以实现不同控件不同背景色。
2、此方法不适用于按纽控件。
二、通过定制来实现不同颜色按纽。
以下通过定制方形彩色按纽来说明:
第一步:派生出自己的按纽类。
//CcolorButton.h
class CColorButton : public CButton
{
DECLARE_DYNAMIC(CColorButton)
public:
CColorButton();
virtual ~CColorButton();
BOOL Attach(const UINT nID, CWnd* pParent,
const COLORREF BGColor = RGB(192, 123, 192), // 按纽的背景色
const COLORREF FGColor = RGB(1, 1, 1), // 文本颜色
);
protected:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDIS); //重定义虚拟函数DrawItem
void DrawFrame(CDC *DC, CRect R); //绘制按纽框
void DrawFilledRect(CDC *DC, CRect R, COLORREF color); //填充按纽框
void DrawLine(CDC *DC, CRect EndPoints, COLORREF color);
void DrawLine(CDC *DC, long left, long top, long right, long bottom, COLORREF color);
void DrawButtonText(CDC *DC, CRect R, const char *Buf, COLORREF TextColor);
//绘制按纽上的文本
COLORREF GetFGColor() { return m_fg; }
COLORREF GetBGColor() { return m_bg; }
private:
COLORREF m_fg, m_bg;
};
#endif <  
说明:本教程来源互联网或网友上传或出版商,仅为学习研究或媒体推广,wanshiok.com不保证资料的完整性。
1/2 1 2 下一页 尾页 |