MFC中App,Doc,MainFrame,View各指針的互相獲取


首先說明這四個類的

執行順序是:App->Doc->MainFrame->View

消息響應順序是:View->Doc->MainFrame->App

 1 // App中獲取其它三項指針
 2 void CSDIApp::OnApp()
 3 {
 4     // App
 5     // Doc
 6     CDocument *pDoc = ((CFrameWndEx *)m_pMainWnd)->GetActiveDocument();//成員變量CFrameWndEx m_pMainWnd
 7     // MainFrame
 8     CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();
 9     // View
10     CView *pView = ((CFrameWndEx *)m_pMainWnd)->GetActiveView();
11 }
12 
13 // Doc中獲取其它三項指針
14 CSDIDoc::CSDIDoc()//構造函數 15 {
16     // App
17     CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();
18     // Doc
19     // MainFrame
20     // Doc的創建先於MainFrame
21     // View
22     // Doc的創建先於View
23 }
24 void CSDIDoc::OnDoc()
25 {
26     // App
27     // 同構造函數
28     // Doc
29     // MainFrame
30     CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();
31     // View
32     CView *pView= (CView *)pMain->GetActiveView();     
33     POSITION pos = GetFirstViewPosition();       
34     pView = GetNextView(pos); 
35 }
36     
37 // MainFrame中獲取其它三項指針
38 CMainFrame::CMainFrame()//構造函數 39 {
40     theApp.m_nAppLook = theApp.GetInt(_T("ApplicationLook"), ID_VIEW_APPLOOK_VS_2005);
41     // App
42     CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();
43     // Doc
44     // 構造函數里無法得到當前激活的Doc
45     // MainFrame
46     // View
47     // 構造函數里無法得到View指針,因為Main先於View創建。
48 }
49 void CMainFrame::OnMain()
50 {
51     // App
52     // 同構造函數
53     // Doc
54     CDocument *pDoc = (CDocument *)GetActiveDocument();
55     // MainFrame
56     // View
57     CView *pView = (CView *)GetActiveView();
58 }
59 
60 // View中獲取其它三項指針
61 CSDIView::CSDIView()//構造函數 62 {
63     // App
64     CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();
65     // Doc
66     /* 無法在View的構造函數里得到Doc指針
67        GetDocument();實際上是返回m_pDocument
68        m_pDocument在OnCreate();里創建        */
69     //CDocument *pDoc = GetDocument();
70     // MainFrame
71     // 構造函數里無法得到MainFrame指針
72     // CFrameWndEx *pMain = (CFrameWndEx *)pApp->m_pMainWnd;
73     // View
74 }
75 void CSDIView::OnView()
76 {
77     // App
78     // 同構造函數
79     // Doc
80     CDocument *pDoc = GetDocument();
81     // MainFrame
82     CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();
83     // View
84 }
85 
86 // Dlg中獲取指針
87 CDlg::CDlg(CWnd* pParent /*=NULL*/)//構造函數 88     : CDialog(CDlg::IDD, pParent)
89 {
90     // App
91     CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();
92     // Doc
93     CDocument *pDoc = ((CFrameWndEx *)AfxGetMainWnd())->GetActiveDocument();
94     // MainFrame
95     CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();
96     // View
97     CView *pView = ((CFrameWndEx *)AfxGetMainWnd())->GetActiveView();
98 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM