创建透明CEdit控件

时间:2020-12-15 08:52:58

1.在资源编辑器中将Edit控件的Border设为none(当然也可以在代码中修改窗口样式)

2.在重载CEdit的类中响应MSG_OCM_CTLCOLOREDIT消息,在处理函数中将背景模式设为透明,否则无法显示背景画刷填充效果

3.从父窗口截取控件对应位置的图片,以此图片创建画刷作为控件的背景画刷返回

4.在Edit的EN_CHANGE处理中调用Invalidate(),否则由于第一步的操作,会导致文本重叠

相关代码如下

// ACEdit.h

#pragma once

#include "ACListWnd.h"

class CACEdit : public CWindowImpl<CACEdit, CEdit> {
public:
CACEdit();
virtual ~CACEdit(); protected:
BEGIN_MSG_MAP_EX(CACEdit)
REFLECTED_COMMAND_CODE_HANDLER(EN_CHANGE, OnChange)
MSG_OCM_CTLCOLOREDIT(OnCtlColorEdit)
DEFAULT_REFLECTION_HANDLER()
END_MSG_MAP() LRESULT OnChange(UINT wNotifyCode, UINT wID, HWND hWndCtl, BOOL& bHandled);
LRESULT OnCtlColorEdit(HDC hDC, HWND hWnd); private:
CDC m_dcBk;
CBitmap m_bmpBk;
CBrush* m_pbkBrush;
};
// ACEdit.cpp

#include "stdafx.h"
#include "ACEdit.h" CACEdit::CACEdit() {
m_pbkBrush = NULL;
} CACEdit::~CACEdit() {
} LRESULT CACEdit::OnChange(UINT wNotifyCode, UINT wID, HWND hWndCtl, BOOL& bHandled) {
Invalidate();
return ;
} LRESULT CACEdit::OnCtlColorEdit(HDC hDC, HWND hWnd) {
SetBkMode(hDC, TRANSPARENT);
if(NULL == m_pbkBrush) {
CRect rect;
GetClientRect(rect);
CRect rect1;
CClientDC clDC(GetParent());
GetWindowRect(rect1);
GetParent().ScreenToClient(rect1);
m_dcBk.CreateCompatibleDC(clDC); m_backBmp.CreateCompatibleBitmap(clDC, rect.Width(), rect.Height());
m_dcBk.SelectBitmap(m_backBmp);
m_dcBk.BitBlt(,,rect.Width(),rect.Height(),clDC,rect1.left,rect1.top,SRCCOPY);
m_pbkBrush = new CBrush(CreatePatternBrush((HBITMAP)m_backBmp));
}
return (LRESULT)(m_pbkBrush->m_hBrush);
}

贴张效果图

创建透明CEdit控件