MFC中App、Doc、MainFrame、View各指针的互相获取

今天读到一篇特别好的文章,内容精炼,句句干货,分享给大家,原文转自
MFC中App、Doc、MainFrame、View各指针的互相获取

首先说明这四个类的执行顺序是:App->Doc->MainFrame->View

消息响应顺序是:View->Doc->MainFrame->App

// App中获取其它三项指针
void CSDIApp::OnApp()
{
    // App
    // Doc
    CDocument *pDoc = ((CFrameWndEx *)m_pMainWnd)->GetActiveDocument();//成员变量CFrameWndEx m_pMainWnd
    // MainFrame
    CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();
    // View
    CView *pView = ((CFrameWndEx *)m_pMainWnd)->GetActiveView();
}

// Doc中获取其它三项指针
CSDIDoc::CSDIDoc()//构造函数
{
    // App
    CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();
    // Doc
    // MainFrame
    // Doc的创建先于MainFrame
    // View
    // Doc的创建先于View
}
void CSDIDoc::OnDoc()
{
    // App
    // 同构造函数
    // Doc
    // MainFrame
    CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();
    // View
    CView *pView= (CView *)pMain->GetActiveView();     
    POSITION pos = GetFirstViewPosition();       
    pView = GetNextView(pos); 
}

// MainFrame中获取其它三项指针
CMainFrame::CMainFrame()//构造函数
{
    theApp.m_nAppLook = theApp.GetInt(_T("ApplicationLook"), ID_VIEW_APPLOOK_VS_2005);
    // App
    CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();
    // Doc
    // 构造函数里无法得到当前激活的Doc
    // MainFrame
    // View
    // 构造函数里无法得到View指针,因为Main先于View创建。
}
void CMainFrame::OnMain()
{
    // App
    // 同构造函数
    // Doc
    CDocument *pDoc = (CDocument *)GetActiveDocument();
    // MainFrame
    // View
    CView *pView = (CView *)GetActiveView();
}

// View中获取其它三项指针
CSDIView::CSDIView()//构造函数
{
    // App
    CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();
    // Doc
    /* 无法在View的构造函数里得到Doc指针
       GetDocument();实际上是返回m_pDocument
       m_pDocument在OnCreate();里创建        */
    //CDocument *pDoc = GetDocument();
    // MainFrame
    // 构造函数里无法得到MainFrame指针
    // CFrameWndEx *pMain = (CFrameWndEx *)pApp->m_pMainWnd;
    // View
}
void CSDIView::OnView()
{
    // App
    // 同构造函数
    // Doc
    CDocument *pDoc = GetDocument();
    // MainFrame
    CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();
    // View
}

// Dlg中获取指针
CDlg::CDlg(CWnd* pParent /*=NULL*/)//构造函数
    : CDialog(CDlg::IDD, pParent)
{
    // App
    CWinAppEx *pApp = (CWinAppEx *)AfxGetApp();
    // Doc
    CDocument *pDoc = ((CFrameWndEx *)AfxGetMainWnd())->GetActiveDocument();
    // MainFrame
    CFrameWndEx *pMain = (CFrameWndEx *)AfxGetMainWnd();
    // View
    CView *pView = ((CFrameWndEx *)AfxGetMainWnd())->GetActiveView();
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值