一、视图窗口作用
提供一个专门用于显示数据的窗口,并和用户进行交互
二、相关类
CView类,(父类为CWnd),封装了关于视图窗口的各种操作
三、视图窗口的使用
1、添加画图的宏
ON_WM_PAINT()
2、声明该方法
afx_msg void OnPaint();
3、重写方法
void CMyFrameWnd::OnPaint() { PAINTSTRUCT ps = { 0 }; HDC hdc = ::BeginPaint(this->m_hWnd, &ps); ::TextOut(hdc, 100, 100, "我是框架窗口客户区", strlen("我是框架窗口客户区")); ::EndPaint(this->m_hWnd, &ps); }
4、运行效果:
5、添加创建宏
ON_WM_CREATE()
6、申明该方法
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
7、重写该方法
int CMyFrameWnd::OnCreate(LPCREATESTRUCT lpCreateStruct) { CMyView* pView = new CMyView; pView->Create(NULL, "MFCView", WS_CHILD | WS_VISIBLE | WS_BORDER, CRect(0, 0, 200, 200), this, AFX_IDW_PANE_FIRST); this->m_pViewActive = pView; return CFrameWnd::OnCreate(lpCreateStruct); }
8、CMyview是抽象的,需要重写OnDraw方法
class CMyView :public CView { public: virtual void OnDraw(CDC* pDC); }; void CMyView::OnDraw(CDC* pDC) { }
9、命令消息(WM_COMMAND)的处理顺序,
View-->Frame-->App
10、新建一个菜单栏,测试上面的处理顺序
#include <afxwin.h> #include "resource.h" //新建视图类 class CMyView :public CView { DECLARE_MESSAGE_MAP() public: virtual void OnDraw(CDC* pDC); afx_msg void OnPaint(); afx_msg void OnNew(); }; BEGIN_MESSAGE_MAP(CMyView, CView) ON_COMMAND(ID_XJ, OnNew) ON_WM_PAINT() END_MESSAGE_MAP() void CMyView::OnNew() { AfxMessageBox("视图类处理了新建被点击发出的COMMAND消息"); } void CMyView::OnPaint() { PAINTSTRUCT ps = { 0 }; HDC hdc = ::BeginPaint(this->m_hWnd, &ps); ::TextOut(hdc, 200, 200, "CMyView::OnPaint", strlen("CMyView::OnPaint")); ::EndPaint(this->m_hWnd, &ps); } void CMyView::OnDraw(CDC* pDC) { //在视图窗口画图 pDC->TextOut(100, 100, "CMyView::OnDraw"); } //框架类 class CMyFrameWnd :public CFrameWnd { DECLARE_MESSAGE_MAP() public: afx_msg void OnPaint(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); }; BEGIN_MESSAGE_MAP(CMyFrameWnd, CFrameWnd) ON_WM_PAINT() ON_WM_CREATE() END_MESSAGE_MAP() int CMyFrameWnd::OnCreate(LPCREATESTRUCT lpCreateStruct) { CMyView* pView = new CMyView; pView->Create(NULL, "MFCView", WS_CHILD | WS_VISIBLE | WS_BORDER, CRect(0, 0, 200, 200), this, AFX_IDW_PANE_FIRST); //默认选中视图窗口 this->m_pViewActive = pView; return CFrameWnd::OnCreate(lpCreateStruct); } //画图 void CMyFrameWnd::OnPaint() { PAINTSTRUCT ps = { 0 }; HDC hdc = ::BeginPaint(this->m_hWnd, &ps); ::TextOut(hdc, 100, 100, "我是框架窗口客户区", strlen("我是框架窗口客户区")); ::EndPaint(this->m_hWnd, &ps); } //应用类 class CMyWinApp :public CWinApp { public: virtual BOOL InitInstance(); }; CMyWinApp theApp; BOOL CMyWinApp::InitInstance() { CMyFrameWnd* pFrame = new CMyFrameWnd; pFrame->Create(NULL, "视图窗口", WS_OVERLAPPEDWINDOW, CFrameWnd::rectDefault, NULL, MAKEINTRESOURCE(IDR_MENU1)); m_pMainWnd = pFrame; pFrame->ShowWindow(SW_SHOW); pFrame->UpdateData(); return TRUE; }
11、运行结果