首页 > 代码库 > 【VC】实现CWnd类的自定义,并实现自定义控件!

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


本例实现一个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工程。




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