我在视图类的WM_CREATE消息的响应函数OnCreate中用如下代码获取CMainFrame的指针时总是报错,说Access Violation:
CMainFrame * pFrame=(CMainFrame *)AfxGetApp()->m_pMainWnd;
或者CMainFrame * pFrame=(CMainFrame *)AfxGetMainWnd();跟踪后发现pFrame的地址是空的,是0x00000000,后面再用pFrame访问框架类时就报的上述错误,别人同样的代码都可以,而且我在别的非初始化的函数中又是正常的,这是怎么回事啊?视图类创建时,框架类不早创建了吗?

解决方案 »

  1.   

    对于SDI   
      int   CMyView::OnCreate(LPCREATESTRUCT   lpcs)   
      {   
              CCreateContext*   pContext   =   (CCreateContext*)lpcs->lpCreateParams;     
      }           
      对于MDI   
      int   CMyView::OnCreate(LPCREATESTRUCT   lpcs)   
      {   
              MDICREATESTRUCT*   lpmcs;   
              lpmcs   =   (MDICREATESTRUCT*)lpCreateStruct->lpCreateParams;     
              CCreateContext*   pContext   =   (CCreateContext*)lpmcs->lParam;     
      }         
    之后
              CDocument*   pDoc=pContext->m_pCurrentDoc;
              CFrameWnd*   pFrame=pContext->m_pCurrentFrame;
      

  2.   

    CYourDlg *pDlg = (CYourDlg *)AfxGetApp()->GetMainWnd();
    pDlg->...
      

  3.   

    可以参考下这个:
    =====================
    A CCreateContext structure contains pointers to the document, the frame window, the view, and the document template. It also contains a pointer to a CRuntimeClass that identifies the type of view to create. The run-time class information and the current document pointer are used to create a new view dynamically. The following table suggests how and when each CCreateContext member might be used:
    ----------
    Member What it is for 
    m_pNewViewClass--- CRuntimeClass of the new view to create. 
    m_pCurrentDoc--- The existing document to be associated with the new view. 
    m_pNewDocTemplate--- The document template associated with the creation of a new MDI frame window. 
    m_pLastView--- The original view upon which additional views are modeled, as in the creation of a splitter window’s views or the creation of a second view on a document. 
    m_pCurrentFrame--- The frame window upon which additional frame windows are modeled, as in the creation of a second frame window on a document.