解决方案:重载CEdit,处理“=WM_CTLCOLOR” + “WM_NCPAINT”
强调“= WM_CTLCOLOR”是消息反射的,是WM_NCPAINT而不是WM_PAINT!
完整代码:
MyEdit.h
//####################################################################
// Comments: 圆角Edit控件
//
// UpdateLogs:
//####################################################################
#pragma once
class CMyEdit : public CEdit
{
DECLARE_DYNAMIC(CMyEdit)
public:
CMyEdit();
virtual ~CMyEdit();
protected:
DECLARE_MESSAGE_MAP()
private:
COLORREF m_clrBackground; //背景颜色
COLORREF m_clrFrame; //边框颜色
COLORREF m_clrText; //文字颜色
COLORREF m_clrDisableBkg; //禁用背景色
COLORREF m_clrDisableTxt; //禁用文字色
CBrush m_brushBkg; //背景画刷
CFont* m_pfTitle;
public:
afx_msg void OnNcPaint();
afx_msg HBRUSH CtlColor(CDC* /*pDC*/, UINT /*nCtlColor*/);
};
MyEdit.cpp:
//####################################################################
// Comments: 圆角Edit控件
//
// UpdateLogs:
//####################################################################
#include "stdafx.h"
#include "MyEdit.h"
#include "../MemDC.h"
#include "../CommonFunc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
IMPLEMENT_DYNAMIC(CMyEdit, CEdit)
CMyEdit::CMyEdit()
{
//m_crText = RGB(40, 40, 40);
//m_crBorder = RGB(228,228,228);
m_clrBackground = RGB(255, 255, 255); //背景颜色
m_clrFrame = RGB(228, 228, 228); //边框颜色
m_clrText = RGB(174, 174, 174); //文字颜色
m_clrDisableTxt = RGB(200, 200, 200); //禁用文字色
m_clrDisableBkg = RGB(255, 255, 255); //禁用背景色
m_brushBkg.CreateSolidBrush(m_clrBackground); //创建背景画刷
m_pfTitle = ::GetFont(_T("微软雅黑"), 12);
}
CMyEdit::~CMyEdit()
{
}
BEGIN_MESSAGE_MAP(CMyEdit, CEdit)
ON_WM_NCPAINT()
ON_WM_CTLCOLOR_REFLECT()
END_MESSAGE_MAP()
// CWEEditCtrl 消息处理程序
HBRUSH CMyEdit::CtlColor(CDC* pDC, UINT /*nCtlColor*/)
{
//pDC->SetBkMode(TRANSPARENT);
if(IsWindowEnabled())
{
m_brushBkg.DeleteObject();
m_brushBkg.CreateSolidBrush(m_clrBackground);
pDC->SetTextColor(m_clrText); //设置文字颜色
pDC->SetBkColor(m_clrBackground); //设置背景色
}
else
{
m_brushBkg.DeleteObject();
m_brushBkg.CreateSolidBrush(m_clrDisableBkg);
pDC->SetTextColor(m_clrDisableTxt); //设置文字颜色
pDC->SetBkColor(m_clrDisableBkg); //设置背景色
}
return (HBRUSH)m_brushBkg.GetSafeHandle();
}
void CMyEdit::OnNcPaint()
{
CRect rectEdit;
CDC* pDC = GetWindowDC();
//设置编辑框的区域
GetWindowRect(rectEdit);
ScreenToClient(rectEdit);
rectEdit.OffsetRect(CSize(2, 2));
CPen mypen, *oldpen;
mypen.CreatePen(PS_SOLID, 1, m_clrFrame);
oldpen = pDC->SelectObject(&mypen);
CPoint point(7, 7);
pDC->RoundRect(rectEdit, point);
pDC->SelectObject(oldpen);
//设置字体
SetFont(m_pfTitle);
ReleaseDC(pDC);
}
使用方法:1、包含头文件
2、申明CMyEdit变量
3、DDX_Control 绑定变量与资源ID