首页 > 代码库 > MFC中App,Doc,MainFrame,View各指针的互相获取

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     // View10     CView *pView = ((CFrameWndEx *)m_pMainWnd)->GetActiveView();11 }12 13 // Doc中获取其它三项指针14 CSDIDoc::CSDIDoc()//构造函数15 {16     // App17     CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();18     // Doc19     // MainFrame20     // Doc的创建先于MainFrame21     // View22     // Doc的创建先于View23 }24 void CSDIDoc::OnDoc()25 {26     // App27     // 同构造函数28     // Doc29     // MainFrame30     CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();31     // View32     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     // App42     CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();43     // Doc44     // 构造函数里无法得到当前激活的Doc45     // MainFrame46     // View47     // 构造函数里无法得到View指针,因为Main先于View创建。48 }49 void CMainFrame::OnMain()50 {51     // App52     // 同构造函数53     // Doc54     CDocument *pDoc = (CDocument *)GetActiveDocument();55     // MainFrame56     // View57     CView *pView = (CView *)GetActiveView();58 }59 60 // View中获取其它三项指针61 CSDIView::CSDIView()//构造函数62 {63     // App64     CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();65     // Doc66     /* 无法在View的构造函数里得到Doc指针67        GetDocument();实际上是返回m_pDocument68        m_pDocument在OnCreate();里创建        */69     //CDocument *pDoc = GetDocument();70     // MainFrame71     // 构造函数里无法得到MainFrame指针72     // CFrameWndEx *pMain = (CFrameWndEx *)pApp->m_pMainWnd;73     // View74 }75 void CSDIView::OnView()76 {77     // App78     // 同构造函数79     // Doc80     CDocument *pDoc = GetDocument();81     // MainFrame82     CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();83     // View84 }85 86 // Dlg中获取指针87 CDlg::CDlg(CWnd* pParent /*=NULL*/)//构造函数88     : CDialog(CDlg::IDD, pParent)89 {90     // App91     CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();92     // Doc93     CDocument *pDoc = ((CFrameWndEx *)AfxGetMainWnd())->GetActiveDocument();94     // MainFrame95     CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();96     // View97     CView *pView = ((CFrameWndEx *)AfxGetMainWnd())->GetActiveView();98 }

 

MFC中App,Doc,MainFrame,View各指针的互相获取