MFC自定义控件编写过程
MFC自定义控件编写过程
功能:点击客户区,新建一个灰色的小窗体。点击这个小窗体,弹出一个对话框,其信息为“你点击了自封装的控件”
[1] 自定义类公有继承CWnd类
[2] 在自定义类的头文件中添加DECLARE_DYNCREA TE(MySelfWnd)
在其源文件中添加IMPLEMENT_DYNCREA TE(MySelfWnd, CWnd)
这么做的原因请看候sir《深入浅出MFC》
[3] 覆盖CWnd中的虚函数Create(......)
[4] WM_LBUTTONDOWN添加其消息映射函数
1// MySelfWnd1.h
2class MySelfWnd : public CWnd
3{
4public:
5 MySelfWnd();
6 DECLARE_DYNCREATE(MySelfWnd)
7virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL);
8virtual ~MySelfWnd();
9protected:
10 afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
11 DECLARE_MESSAGE_MAP()
12};
13//MySelfWnd1.cpp
14#include "stdafx.h"
15#include "MySelfWnd.h"
16#include "MySelfWnd1.h"
17MySelfWnd::MySelfWnd()
18{
19
20 }
21MySelfWnd::~MySelfWnd()
22{
23}
24IMPLEMENT_DYNCREATE(MySelfWnd, CWnd)
25BEGIN_MESSAGE_MAP(MySelfWnd, CWnd)
26//{{AFX_MSG_MAP(MySelfWnd)
27 ON_WM_LBUTTONDOWN()
28//}}AFX_MSG_MAP
29END_MESSAGE_MAP()
30void MySelfWnd::OnLButtonDown(UINT nFlags, CPoint point)
31{
32// TODO: Add your message handler code here and/or call default
33 MessageBox("你点击了自封装的控件");
34 CWnd::OnLButtonDown(nFlags, point);
35}
36BOOL MySelfWnd::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext) 37{
38// TODO: Add your specialized code here and/or call the base class
39// 重新注册窗口类,
40 lpszClassName=AfxRegisterWndClass( CS_HREDRAW | CS_VREDRAW , AfxGetApp()->LoadStandardCursor(IDC_ARROW),
41 (HBRUSH)GetStockObject(LTGRAY_BRUSH), NULL) ;
42return CWnd::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext);
43}
44////view类
45void CMySelfWndView::OnLButtonDown(UINT nFlags, CPoint point)
46{
47// TODO: Add your message handler code here and/or call default
48static CRect rect;
49 rect.SetRect(10,10,100,100);
50 myselfwnd=new MySelfWnd ;
51 myselfwnd->Create("non",NULL,WS_CHILDWINDOW | WS_VISIBLE, rect,this,456);
52 CView::OnLButtonDown(nFlags, point);
53}