CEdit、CStatic文字颜色和背景颜色(重写类方式)

1、创建一个CMyEdit类继承CEdit类
如何创建类请参考:

2、在CMyEdit类中添加反射消息:“=WM_CTLCOLOR”
这里注意反射消失前的“=”,切不可错添加为“WM_CTLCOLOR”,“=WM_CTLCOLOR”表示反射消息,响应函数是CtlColor,控件自己发送自己接收。“WM_CTLCOLOR”是接收子控件发给自己的消息,响应函数是OnCtlColor,由于我们使用CMyEdit类自行绘制,所以我们选取反射式消息。
如何在函数中添加消息请参考:

3、具体实现代码
.h文件

#pragma once
#include "afxwin.h"
class CMyEdit :
	public CEdit
{
public:
	CColorEdit();
	~CColorEdit();
 
	void SetForeColor(COLORREF color);
	void SetBkColor(COLORREF color);
	void SetTextFont(int FontHight, LPCTSTR FontName);
 
private:
	COLORREF m_ForeColor;  // text color
	COLORREF m_BackColor;  // background color
	CBrush	 m_BkBrush;	   // background brush
	CFont*	 p_Font;
 
public:
	DECLARE_MESSAGE_MAP()
	afx_msg HBRUSH CtlColor(CDC* /*pDC*/, UINT /*nCtlColor*/);
};

.cpp文件

#include "stdafx.h"
#include "CMyEdit.h"
 
 
CMyEdit::CMyEdit()
{
	m_ForeColor = RGB(0, 0, 0);
	m_BackColor = RGB(240, 240, 240);
	m_BkBrush.CreateSolidBrush(m_BackColor);
	p_Font = NULL;
}
 
CMyEdit::~CMyEdit()
{
	if (p_Font){
		delete p_Font;
	}
}
 
BEGIN_MESSAGE_MAP(CColorEdit, CEdit)
	ON_WM_CTLCOLOR_REFLECT()
END_MESSAGE_MAP()
 
HBRUSH CMyEdit::CtlColor(CDC* pDC, UINT nCtlColor)
{
	// TODO:  Change any attributes of the DC here
	pDC->SetTextColor(m_ForeColor);
	pDC->SetBkColor(m_BackColor);
	m_BkBrush.DeleteObject();
	m_BkBrush.CreateSolidBrush(m_BackColor);
 
	// TODO:  Return a non-NULL brush if the parent's handler should not be called
	return (HBRUSH)m_BkBrush.GetSafeHandle();
}
 
void CMyEdit::SetForeColor(COLORREF color){
	m_ForeColor = color;
}
 
void CMyEdit::SetBkColor(COLORREF color){
	m_BackColor = color;
}
 
void CMyEdit::SetTextFont(int FontHight, LPCTSTR FontName){
	if (p_Font){
		delete p_Font;
	}
	p_Font = new CFont;
	p_Font->CreatePointFont(FontHight, FontName);
	SetFont(p_Font);
 
}

4、测试
将原先添加的控件变量类型修改成我们刚刚创建的类型

class CMyEditerDlg : public CDialogEx
{
 ...
	DECLARE_MESSAGE_MAP()
public:
	//CEdit m_edit;
	CMyEdit m_edit;
};

在使用时调用函数进行颜色设置,例如设置背景色,下面三行代码是重绘和刷新,可以将这三行代码集成到SetColor中,实现立即刷新显示。修改控件中的字体和颜色也是同理。

	m_edit.SetBkColor(RGB(255, 96, 96));
	m_edit.SetRedraw(TRUE);
	m_edit.Invalidate();
	m_edit.UpdateWindow();

你可能感兴趣的:(CEdit、CStatic文字颜色和背景颜色(重写类方式))