MFC中獲取App,MainFrame,Doc和View類等指針的方法


 

MFC中獲取App,MainFrame,Doc和View類等指針的方法

1  獲取應用程序類(App)指針

在任何類中都可用MFC全局函數AfxGetApp()獲得

2 獲取框架類(MainFrame)指針

1)在App中獲得MainFrame指針
CWinApp 中的  m_pMainWnd變量就是MainFrame的指針
也可以: CMainFrame *pMain =(CMainFrame  *)AfxGetMainWnd();

2) 在View中獲得MainFrame指針 

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

3 獲取各種視圖類(View)指針

1)(在App,MainFrame,Doc中)獲取當前已建立View

CMainFrame *pMain = (CMainFrame *)AfxGetApp()->m_pMainWnd;
CMyView *pView = (CMyView *)pMain->GetActiveView();

2)從文檔類(Doc)取得視圖類(View)的指針----多視

CDocument類提供了兩個函數用於視圖類的定位:GetFirstViewPosition()和GetNextView() 

virtual POSITION GetFirstViewPosition() const;
virtual  CView* GetNextView(POSITION& rPosition) const;

例:CTestView* pTestView;    POSITION pos=GetFirstViewPosition();     pTestView=GetNextView(pos);

為了方便,我們將其作為一個文檔類的成員函數,它有一個參數,表示要獲得哪個類的指針。實現如下: 

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("Cannot Locate the View!");

return NULL;

}

return pView;

}

3)從一個視圖類取得另一視圖類的指針

用文檔類作中轉,先得到文檔類的指針,再用文檔類的視圖定位函數取得另一個視圖類。同樣,可以實現成一個函數:
(假設要從CTestAView中取得指向其它視圖類的指針)

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("Cannot Locate the View!");

return NULL;

}

return pView;

}

4)獲取分割視圖中各個視圖的指針
CSplitterWnd  m_wndSplitter;
m_wndSplitter.CreateStatic(this, 1,  2);//分割成一行兩列
m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CLeftPaneView),  CSize(10, 10), pContext);
m_wndSplitter.CreateView(0, 1,  RUNTIME_CLASS(CRightPaneFrame), CSize(0, 0),  pContext);
//獲取左邊視圖的兩種方法
CLeftPaneView* pLeftPaneView     =  (CLeftPaneView*)    m_wndSplitter.GetPane(0,0);
//上一句可以用下句代替:
//CLeftPaneView* pLeftPaneView   = (CLeftPaneView *)GetActiveView();
//獲取右邊視圖

pLeftPaneView->m_pRightPaneFrame = (CRightPaneFrame*)  m_wndSplitter.GetPane(0,1);

4 獲取各種文檔類(Doc)和文檔模板類的指針

1)獲得當前文檔指針       CDocument * pCurrentDoc = (CFrameWnd  *)m_pMainWnd->GetActiveDocument();

2)從文檔模板獲得文檔類指針

一個文檔模板可以有多個文檔,每個文檔模板都保留並維護了一個所有對應文檔的指針列表。 

用CDocTemplate::GetFirstDocPosition函數獲得與文檔模板相關的文檔集合中第一個文檔的位置,並用POSITION值作為CDocTemplate::GetNextDoc的參數來重復遍歷與模板相關的文檔列表。函數原形為: 

virtual POSITION GetFirstDocPosition( ) const = 0; 

virtual CDocument *GetNextDoc(POSITION & rPos) const = 0;  

如果列表為空,則rPos被置為NULL.

3)在文檔類中獲得文檔模板指針

在文檔中可以調用CDocument::GetDocTemplate獲得指向該文檔模板的指針。

函數原形如下: CDocTemplate * GetDocTemplate ( )  const; 
如果該文檔不屬於文檔模板管理,則返回值為NULL。

http://blog.csdn.net/puncha/article/details/17394885


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM