【VC】实现CWnd类的自定义,并实现自定义控件!

VC++ 专栏收录该内容
102 篇文章 0 订阅


本例实现一个ColorWnd类,实现通过鼠标单击,刷新不同的颜色背景。


class CColorWnd : public CWnd
{
	DECLARE_DYNAMIC(CColorWnd)

public:
	CColorWnd();
	virtual ~CColorWnd();
	virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
	afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
	afx_msg void OnPaint();

protected:
	DECLARE_MESSAGE_MAP()

public:
	BOOL Create(CRect rcLayout,CWnd *pParenWnd,UINT nID,DWORD dwStyle = WS_CHILD|WS_VISIBLE);	
	
};


MPLEMENT_DYNAMIC(CColorWnd, CWnd)

CColorWnd::CColorWnd()
{

}

CColorWnd::~CColorWnd()
{

}

BEGIN_MESSAGE_MAP(CColorWnd, CWnd)
	ON_WM_PAINT()
	ON_WM_SIZE()
	ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

BOOL CColorWnd::PreCreateWindow(CREATESTRUCT& cs)
{
	WNDCLASS wndcls;
	memset(&wndcls, 0, sizeof(WNDCLASS));

	wndcls.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_NOCLOSE;
	wndcls.lpfnWndProc = ::DefWindowProc; 
	wndcls.hInstance = AfxGetInstanceHandle();
	wndcls.hIcon =  NULL; 
	wndcls.hCursor =NULL;
	wndcls.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
	wndcls.lpszMenuName = NULL;
	wndcls.lpszClassName = _T("ColorWnd");
	if(!AfxRegisterClass(&wndcls))
	{
		TRACE("Class Registration Failed!\n");
		return FALSE;
	}
	cs.lpszClass = wndcls.lpszClassName;

	return CWnd::PreCreateWindow(cs);
}

BOOL CColorWnd::Create(CRect rcLayout,CWnd *pParenWnd,UINT nID,DWORD dwStyle)
{
	if (rcLayout.Width() < 50)
	{
		rcLayout.right += 40;
	}
	LPCTSTR lpszClassName = AfxRegisterWndClass(NULL,LoadCursor(NULL, IDC_ARROW),(HBRUSH)GetStockObject(NULL_BRUSH));

	return CWnd::Create(lpszClassName,NULL,dwStyle,rcLayout,pParenWnd,nID,NULL);
}

void CColorWnd::OnLButtonDown(UINT nFlags, CPoint point)
{
	Invalidate(TRUE);

	CWnd::OnLButtonDown(nFlags, point);
}

void CColorWnd::OnPaint()
{
	CPaintDC dc(this);
	CRect rcWnd;
	GetWindowRect(&rcWnd);
	rcWnd.SetRect(0,0,rcWnd.Width(),rcWnd.Height());

	int nRed = rand()%255;
	int nBlue = rand()%255;
	
	CBrush brush(RGB(nRed,nBlue,0));
	dc.FillRect(rcWnd,&brush);
	brush.DeleteObject();	
}


CColorWnd m_ColorWnd;

m_ColorWnd.Create(CRect(300,150,350,180),this,1202);

通过鼠标单击m_ColorWnd的区域,实现自动刷新背景色! 本例是Dialog工程。




  • 1
    点赞
  • 0
    评论
  • 3
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

shen_wei

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值