现在的位置: 首页 > 综合 > 正文

MFC中的CApp,CMainFrame,CDoc,CView

2014年10月31日 ⁄ 综合 ⁄ 共 2277字 ⁄ 字号 评论关闭

MFC中的CApp,CMainFrame,CDoc,CView

| 求索阁 发表于 2012-08-27 23:10 | 本文阅读1993次 | 
CMainFrame是CApp类的主程序窗口(如果是选MDI或SDI结构的话),也就是程序的一个框架。 

CApp中如无特殊的要求不用加什么代码,CMainFrame中也是根据需要,如按照微软提供的框架也不需要加什么代码。    

CDocument一般和CView一起使用,这样的程序叫文档/视图结构。 

CDocument中加的代码主要是和你的文档内容有关的,如文档中信息(对象)等,需要处理的一般有文档内容的编辑、删除、添加、序列化(读写文件)等方面的代码。    

CView的工作就是把你的CDocument中的内容显示在文档上,主要处理的是显示方面的工作。  

AfxGetApp()函数可以得到CApp指针。    

CApp->GetMainWnd()函数可以得到CMainFrame指针。    

在CDocument或CView中调用的写法是AfxGetApp()->GetMainWnd()    

CMainFrame中可以用GetActiveView()函数得到活动CView的指针。    

CView中可以用GetDocument得到CDocument的指针。 

假设你是单文档单个VIEW的程序。那么: 

1)CMainFrame: 

GetActiveView()可得到View指针。 

GetActiveDocument()可得到Document指针。 

2)CDoc: 

POSITION pos = GetFirstViewPosition(); 

CView* pView = GetNextView(pos); //得到View指针 

AfxGetMainWnd()可得到MainFrame指针 

3) CView: 

GetDocument()可得到CDoc指针。 

AfxGetMainWnd()可得到MainFrame指针。 

—————– 

CWinApp *AfxGetApp()是一个全局函数,在任何地方都可以获得C***App类对象的指针.

1、//在C***App类中: 

获得CMainFrame类对象的指针: 

CMainFrame* pMain=(CMainFrame*)CWinThread::m_pMainWnd; 

获得C***View类对象的指针: 

(假设只有一个视图,须通过CMainFrame) 

C***View *pView=(C***View *)((CMainFrame*)m_pMainWnd)->CFrameWnd::GetActiveView(); 

获得C***Doc类对象的指针(须通过CMainFrame) 

C***Doc *pDoc=(C***Doc *)((CMainFrame*)m_pMainWnd)->CFrameWnd::GetActiveDocument();

2、 //在CMainFrame类中: 

获得CMainFrame类对象的指针: 

CMainFrame* pMain=(CMainFrame*)CWnd::GetActiveWindow(); 

获得C***View类对象的指针: 

C***View *pView=(C***View *)CFrameWnd::GetActiveView(); 

获得C***Doc类对象的指针 C***Doc *pDoc=(C***Doc *)CFrameWnd::GetActiveDocument();

3、 //在C***Doc类中: 

获得CMainFrame类对象的指针: 

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

CMainFrame* pMain=(CMainFrame*)AfxGetApp()->m_pMainWnd; 

获得C***View类对象的指针: 

(假设只有一个视图,须通过CMainFrame) 

C***View *pView=(C***View *)((CMainFrame*)AfxGetApp()->m_pMainWnd)->CFrameWnd::GetActiveView(): 

(假设有两个以上视图,以找寻C***View为例) POSITION pos=CDocument::GetFirstViewPosition(); 

while(pos != NULL) 



    CView *pView=CDocument::GetNextView(pos); 

    if(pView->GetRuntimeClass()==RUNTIME_CLASS(C**View)) 

   {} 

}

4、 //在C***View类中: 

获得CMainFrame类对象的指针: 

CMainFrame* pMain=(CMainFrame*)AfxGetMainWnd(); CMainFrame* pMain=(CMainFrame*)CWnd::GetParentFrame(); 

CMainFrame* pMain=(CMainFrame*)AfxGetApp()->m_pMainWnd; 

获得C***Doc类对象的指针 

C***Doc *pDoc= GetDocument();

注意: 

1 在CFrameWnd::ActivateFrame函数之后可以取得CMainFrame * 

2 在CView::OnCreate函数执行完毕后,可以查找C***View * 

3 在CView::OnCreate函数执行完毕后,可以取得C***Doc *

抱歉!评论已关闭.