自绘edit控件的边框,实现点中边框高亮的状态

1.edit控件没有DrawItem函数,客户区域的自绘需要在OnPaint()中完成,而非客户区域的自绘要在OnNcPaint()中完成


2.edit控件的边框有2中状态,鼠标点中的状态和常态。这里依然用OnMouseMove和OnMouseLeave来追踪鼠标时在edit控件里面,还是外面。

3.实现代码如下:

MyEdit.h

#pragma once
#ifndef _H_MYEDIT_H
#define _H_MYEDIT_H

class CMyEdit :public CEdit
{
	DECLARE_DYNAMIC(CMyEdit)
public:
	CMyEdit(void);
	~CMyEdit(void);
	void DrawFrame();
protected:

	afx_msg void OnMouseLeave();
	afx_msg void OnMouseMove(UINT nFlags, CPoint point);
	afx_msg void  OnNcPaint();
 	afx_msg void  OnPaint();
	DECLARE_MESSAGE_MAP()

public:
	bool m_isinedit;
	CBrush m_normalbrush1;
	CBrush m_normalbrush2;
	CBrush m_hoverbrush1;
	CBrush m_hoverbrush2;
};

#endif

MyEdit.cpp

#include "MyEdit.h"

IMPLEMENT_DYNAMIC(CMyEdit, CEdit)
CMyEdit::CMyEdit(void)
{
	m_isinedit=false;
	/*为了实现qq编辑框的高亮颜色效果,这里画刷的颜色借鉴csdn界面版的版主大人CometNet的demo,
	我个人不是很清楚这颜色怎么调配*/
	m_hoverbrush1.CreateSolidBrush(0xFDC860);
    m_hoverbrush2.CreateSolidBrush(0xE7AC49);
	m_normalbrush1.CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
	m_normalbrush2.CreateSolidBrush(GetSysColor(COLOR_WINDOWFRAME));
}


CMyEdit::~CMyEdit(void)
{
}

BEGIN_MESSAGE_MAP(CMyEdit, CEdit)
	ON_WM_MOUSEMOVE()
	ON_WM_MOUSELEAVE()
	ON_WM_NCPAINT()
	ON_WM_PAINT()
END_MESSAGE_MAP()

void CMyEdit::OnMouseMove(UINT nFlags, CPoint point)
{
	if (!m_isinedit)
	{
		TRACKMOUSEEVENT mouseevent;
		mouseevent.cbSize=sizeof(mouseevent);
		mouseevent.dwFlags=TME_LEAVE;
		mouseevent.dwHoverTime=10;
		mouseevent.hwndTrack=m_hWnd;
		_TrackMouseEvent(&mouseevent);
		m_isinedit=true;
		DrawFrame();
	}
	CEdit::OnMouseMove(nFlags, point);
}

void CMyEdit::OnMouseLeave()
{
	m_isinedit=false;
	DrawFrame();
	CEdit::OnMouseLeave();
}

void CMyEdit::OnNcPaint()
{
	CEdit::OnNcPaint();//先调用基类的OnNcPaint()让系统画图,系统画完后再我们画
	DrawFrame();
}

void  CMyEdit::OnPaint()
{
	CEdit::OnPaint();
}

void CMyEdit::DrawFrame()
{
	/* GetWindowDC 获取的是当前窗口的设备场景,注意是整个窗口,并不是客户区或者是桌面的设备场景.
	GetWindowDC 获取到的设备场景,起始坐标(左、上)都是为零(相对于整个窗口);而GetWindowRect 
	获取的坐标是窗口相对于桌面来计算的,再 OffsetRect 为的就是初始化这个窗口绘图矩形,使rect的起始坐标
	和GetWindowDC 获取到的设备场景的起始坐标重合*/
	CDC* pDC = GetWindowDC( );
	CRect rect;
	GetWindowRect( &rect);
	rect.OffsetRect( -rect.left, -rect.top);
	if (m_isinedit)
	{
		pDC->FrameRect( &rect, &m_hoverbrush1);//先画外层边框
		rect.InflateRect(-1,-1);
		pDC->FrameRect( &rect, &m_hoverbrush2);//再画内层边框
	
	}
	else
	{
		pDC->FrameRect( &rect, &m_normalbrush1);//先画外层边框
		rect.InflateRect(-1,-1);
		pDC->FrameRect( &rect, &m_normalbrush2);//再画内层边框
		
	}
	ReleaseDC( pDC);
}


你可能感兴趣的:(自绘edit控件的边框,实现点中边框高亮的状态)