文章目錄
- CWinApp中顯式調用其他類
- CFrameWnd調用其他類
- CView調用其它類
- CDocument調用其它類
- CWinApp中隱式調用CDocument
我們前面有講到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中很多地方就是這樣封裝起來的啊,所以你看著定義了一函數,但不知道是在哪兒被調用的,那就叫一個鬱悶憋屈啊).