目的:MDI中手动新建文档及视图并将视图关联到该文档,
要求:1.不使用::SendMessage(this->m_hWnd,WM_COMMAND,ID_FILE_NEW,NULL)之类的常规方法
      2.最好是修改下面已有的代码实现在MainFrame的某菜单响应函数内:
……
CMyDoc* pDoc = new CMyDoc;
CMyView* pView = new CMyView;
AfxMessageBox("aaa");
pView->Create(NULL, NULL, WS_CHILD | WS_VISIBLE | WS_BORDER, rectDefault, this, AFX_IDW_PANE_FIRST + 1, NULL );
AfxMessageBox("bbb");
pDoc->AddView(pView);
AfxMessageBox("ccc");
SetActiveView(pView);
……现在能正确运行到AfxMessageBox("aaa"),下一步pView->Create()时出现运行时错误!

解决方案 »

  1.   

    视图类有这样动态的创建吗?pView->Create(),我在msdn中怎么没有看到呢
      

  2.   

    CView类从CWnd类派生,你说有没有Create()啊?
      

  3.   

    你首先得明白文档类(CDocument),文档模板类(CDocumentTemplate)及视图类(CView)之间的关系。推荐《MFC经典问答》
      

  4.   

    你只抄了MSDN上的代码.
    Note that if OnSize has been overridden in CMyView2 
    //and GetDocument() is used in this override it can 
    //cause assertions and, if the assertions are ignored,
    //cause access violation.
    这段注释你看了没有.
      

  5.   

    看到了,but i havn't overridden the OnSize in CMyView2, so i havn't used GetDoucument() in the ovveride.
      

  6.   

    变通的解决方案:
    void CMainFrame::Ontemp() 
    {
    // TODO: Add your command handler code here
    POSITION tplPos = AfxGetApp()->GetFirstDocTemplatePosition();
    CDocTemplate* pDocTpl = AfxGetApp()->GetNextDocTemplate(tplPos);
    CDocument* pNewDoc =(CDocument*) pDocTpl->CreateNewDocument();
    CMainFrame* pNewChWnd = (CMainFrame *)(pDocTpl->CreateNewFrame(pNewDoc, NULL));
    pNewChWnd->SetTitle(_T("窗口标题"));
    pNewChWnd->ShowWindow(SW_SHOWNORMAL);
    pNewChWnd->SetFocus();
    }
    pView->Create(NULL, NULL, WS_CHILD | WS_VISIBLE | WS_BORDER, rectDefault, this, AFX_IDW_PANE_FIRST + 1, NULL );
    通不过的原因:在MDI的MainFrame中的this指的是外面的总框架,而pView->Create中的相应参数应当是pParentWnd,在MDI中view的ParentWnd应当是子窗体,也就是CChildFrame。