MFC文档视图(四):类之间的调用

来源:互联网 发布:关于北京知实践园作文 编辑:程序博客网 时间:2024/05/17 02:51

我们前面有讲到4个关键的类CWinApp,CFrameWnd,CView,CDocument是互相关联,那自然会涉及到互相调用.这里为了方便还继承用这个类名字来说明(实际上应该是用继承自它们的子类的)

下面有2个全局函数可以得到CWinApp与CFrameWnd.全局函数嘛就是随便哪里都能调用的了.

1.CWinApp* pApp = AfxGetApp();

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

//你也可以先得到CWinApp然后间接得到CMainFrame* pMain=(CMainFrame*)pApp->m_pMainWnd;

 

 

CWinApp中显式调用其他类

1.CWinApp调用CDocument

方法1:

CWinApp中有一个CSingleDocTemplate的指针,而CSingleDocTemplate中又有指向CDocument的指针.于是乎通过指针一路找下去自然就找着了.

POSITION pos = m_pDocTemplate->GetFirstDocPosition();

CDocument *pDoc = m_pDocTemplate->GetNextDoc(pos);

//其中m_pDocTemplate就是CSingleDocTemplate的指针.这里的POSITION有点类似STL中的iterator(迭代器).

方法2:

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

CDocument* pDoc = (CDocument*)pMain->CFrameWnd::GetActiveDocument(); //通过CFrame间接调用

2.CWinApp调用CView

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

CView* pView = (CView*)pMain->CFrameWnd::GetActiveView(); //通过CFrame间接调用

 

CFrameWnd调用其他类

CView* pView = (CView*)CFrameWnd::GetActiveView();

CDocument* pDoc = (CDocument*)CFrameWnd::GetActiveDocument();

 

CView调用其它类

CMyDocument* pDoc = (CMyDocument*)GetDocument();

 

CDocument调用其它类

POSITION pos=CDocument::GetFirstViewPosition();  //一个文档类可以对应多个CView,但一个CView只对对应一个文档类
while(pos != NULL) { 
CView *pView=CDocument::GetNextView(pos);

}

 

CWinApp中隐式调用CDocument

以命令消息的路由例.本来正常的路由顺序是CView --> CDocument -->CFrameWnd --> CWinApp.

仍为菜单File-->Open发出的消息为例.假如你让类CWinApp来处理这相消息,那么前面3个类就不能处理它了.那假如你只想CWinApp处理一部分.另一部分要其他类处理该咋整呢.

先在CMyWinApp中定义宏

ON_COMMAND(ID_FILE_OPEN, OnFileOpen)

void CMyWinApp:OnFileOpen(){

//做一些部分处理

CString szPath = _T("D:\\Test.txt");

CWinApp::OpenDocumentFile(szPath); //调用父类方法

}

假如类CMyDocument中有重写父类的虚函数BOOL CSessionEditorDoc::OnOpenDocument(LPCTSTR lpszPathName) { }

则在前面调用CWinApp::OpenDocumentFile(szPath)之后,会接着调用OnOpenDocument.(MFC中很多地方就是这样封装起来的啊,所以你看着定义了一函数,但不知道是在哪儿被调用的,那就叫一个郁闷憋屈啊).

0 0
原创粉丝点击