【C++】【MFC】MFC多文档框架

相较于单文档架构,多文档基本架构则是有起码两个框架窗口,与其相对应的也会有两个文档类进行数据管理。

参与架构的类:

  CMDIFrameWnd / CMDIChildWnd / CWinApp / CView / CDocument

需要用的类:

  CDocTemplate(文档模板类)

    |-> CMultiDocTemplate(多文档模板类)

  CDocManager(文档管理类)

 1 #include <afxwin.h>
 2 #include "resource.h"
 3 
 4 class CMyDocument : public CDocument {
 5     DECLARE_DYNCREATE(CMyDocument)
 6 };
 7 IMPLEMENT_DYNCREATE(CMyDocument, CDocument)
 8 
 9 class CMyView : public CView {
10     DECLARE_DYNCREATE(CMyView)
11 public:
12     virtual void OnDraw(CDC* pDC);
13 };
14 IMPLEMENT_DYNCREATE(CMyView, CView)
15 
16 void CMyView::OnDraw(CDC* pDC) {
17     pDC->TextOut(100, 100, "View Window.");
18 }
19 
20 class CMyChild : public CMDIChildWnd {
21     DECLARE_DYNCREATE(CMyChild)
22 };
23 IMPLEMENT_DYNCREATE(CMyChild, CMDIChildWnd)
24 
25 class CMyFrameWnd : public CMDIFrameWnd {
26 
27 };
28 
29 class CMyWinApp : public CWinApp {
30 public:
31     virtual BOOL InitInstance();
32 };
33 
34 BOOL CMyWinApp::InitInstance() {
35     // 主框架窗口创建
36     CMyFrameWnd* pFrame = new CMyFrameWnd;
37     pFrame->LoadFrame(IDR_MENU1);
38     m_pMainWnd = pFrame;
39     pFrame->ShowWindow(SW_SHOW);
40     pFrame->UpdateWindow();
41 
42     // 子框架、视图类、文档类定义、创建、关联
43     CMultiDocTemplate* pTemplate = new CMultiDocTemplate(IDR_MENU2,
44         RUNTIME_CLASS(CMyDocument),
45         RUNTIME_CLASS(CMyChild),
46         RUNTIME_CLASS(CMyView));
47     AddDocTemplate(pTemplate);
48 
49     OnFileNew();
50     OnFileNew();
51     OnFileNew();
52 
53     return true;
54 }
55 
56 CMyWinApp theApp;

Result:

 

执行过程:

theApp
  |-> m_pDocManger(文档管理类)
    |-> m_templateList(文档模板类对象地址)
      |-> CMultiDocTemplate* pTemplate

        | ->m_docList(保存多文档地址)

        | ->m_pDocClass(RUNTIME_CLASS(CMyDoc))

        | ->m_pFrameClass(RUNTIME_CLASS(CMyChild))

        | ->m - pViewClass(RUNTIME_CLASS(CMyView))

OnFileNew() -> 依次创建文档类对象,子框架类对象,子框架类窗口,视图类对象,视图类窗口,文档类对象和视图类对象关联

posted @ 2024-06-24 10:07  VanGoghpeng  阅读(26)  评论(0编辑  收藏  举报