【VC++学习笔记四】MFC应用程序中框架类的获取

一、文档类中

获取视图:

先获取主窗体,在根据主窗体获取视图

pMain->GetActiveDocument();注意类型转换

由于文档中可能包含多个视图,可以按照下面函数获取:

  CView*   CTestDoc::GetView(CRuntimeClass*   pClass) 

  { 

        CView*  pView; 

        POSITION   pos=GetFirstViewPosition(); 

  

        while(pos!=NULL)

       {

              pView=GetNextView(pos); 

              if(!pView->IsKindOf(pClass))

                     break;

       } 

  

        if(!pView->IsKindOf(pClass))

       { 

                 AfxMessageBox("Connt   Locate   the   View./r/n");

                return   NULL;

       }

 

       return   pView; 

  } 

同理如果有多个视图,在一个视图中获取另外一个视图的方法可以如下:

            CView* CTestAView::GetView(CRuntimeClass* pClass) 

CTestDoc* pDoc=(CTestDoc*)GetDocument(); 

CView*    pView; 

POSITION   pos=pDoc->GetFirstViewPosition(); 

while(pos!=NULL)

pView=pDoc->GetNextView(pos); 

if(!pView->IsKindOf(pClass)) 

break; 

if(!pView->IsKindOf(pClass))

AfxMessageBox("Connt Locate the View."); 

return   NULL; 

}

return  pView; 

}

获取主窗体:

CMainFrame *pMain = (CMainFrame *)AfxGetMainWnd();

先获取App,再根据App获取主窗体

CXXXApp *pApp = (CXXXApp *)AfxGetApp();

CMainFrame *pMain = (CMainframe*)pApp->GetMainWnd();

CMainFrame *pMain = (CMainframe*)pApp->m_pMainWnd;

获取App:

CXXXApp *pApp = (CXXXApp *)AfxGetApp();

二、视图类中

获取文档:

GetDocument()

返回的即为对应文档的指针,不是CDocument类,不需要进行类型转换。

获取主窗体:

CMainFrame *pMain = (CMainFrame *)AfxGetMainWnd();

或者先获取App,在根据App获取主窗体

CXXXApp *pApp = (CXXXApp *)AfxGetApp();

CMainFrame *pMain = (CMainframe*)pApp->GetMainWnd();

CMainFrame *pMain = (CMainframe*)pApp->m_pMainWnd;

获取App:

CXXXApp *pApp = (CXXXApp *)AfxGetApp();

三、主窗体中

获取文档:

GetActiveDocument();注意类型转换

获取视图:

GetActiveView();注意类型转换

获取App:

CXXXApp *pApp = (CXXXApp *)AfxGetApp();

四、App类中

获取主窗体:

CMainFrame *pMain = (CMainFrame *)AfxGetMainWnd();

CMainFrame *pMain = (CMainframe*)this->GetMainWnd();

CMainFrame *pMain = (CMainframe*)this->m_pMainWnd;

 

获取视图:

先获取CMainFrame,再根据CMainFrame获取视图:

pMain->GetActiveDocument();注意类型转换

获取文档:

先获取CMainFrame,再根据CMainFrame获取文档:

pMain->GetActiveDocument();注意类型转换

 

五、程序中的其他类中

参考上面的方式,其中App可由AfxGetApp获取,CMainFrame可由AfxGetMainWnd获取,任何地方都可以,Doc和View是属于CMainFrame的两个结构,可以通过CMainFrame获取。

原文地址:https://www.cnblogs.com/OldGlory/p/3978112.html