2011年10月27日 星期四

[MFC] How to get the pointers of Doc,View,MainFrmae,App in SDI, MDI

When developing MFC program on Document/View architecture, the first problem we usually have is how to get the pointers of Doucment, View, MainFrame and App.
Below are some common methods to get the pointers:
  1. Get the pointer of Application Class CWinApp:Use MFC Global Function AfxGetApp() to get it.
     

  2. Get the pointer of MainFrame
    • User member variable: m_pMainWnd
      (
      m_pMainWnd is the member variable of CWinThread, and CWinApp derived from CWinThread, so we can use the member of CWinThread to get the pointer of Main frame )
      CMainFrame* pMainWnd = (CMainFrame*) AfxGetApp()->m_pMainWnd;
    • Use MFC Global Function AfxGetMainWnd() to get it.
      CMainFrame* pMainWnd =(CMainFrame*) AfxGetMainWnd();
  3. Get the pointer of Document in View
    Us
    e the member function GetDocument() to get it.
    CMyAppDoc*
    pDoc = GetDocument();
  4. Get the pointer of Active View
    First,
    get the pointer of MainFrame, and then use GetActiveView() to get the pointer of View by MainFrame.
    CMainFrame* pMainWnd = (CMainFrame*) AfxGetApp()->m_pMainWnd; 
    CMyAppView* pView = ( CMyAppView*) pMainWnd->GetActiveView();
  5. Get the pointer of Active Document
    First,
    get the pointer of FrameWnd, and then use GetActiveDocument() to get the pointer of Document by FrameWnd.
    CFrameWnd* pMainFrm = (CFrameWnd*) AfxGetApp()->m_pMainWnd;
    CDocument* pCurDoc = (CFrameWnd*) pMainFrm ->GetActiveDocument();


沒有留言:

張貼留言