单文档打开操作

ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen)
void CWinApp::OnFileOpen()
{
    ENSURE(m_pDocManager != NULL);
    m_pDocManager->OnFileOpen();
}
CDocManager* m_pDocManager;
void CDocManager::OnFileOpen()
{
    // prompt the user (with all document templates)
    CString newName;
    if (!DoPromptFileName(newName, AFX_IDS_OPENFILE,
      OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, TRUE, NULL))
        return; // open cancelled

    AfxGetApp()->OpenDocumentFile(newName);
        // if returns NULL, the user has already been alerted
}
BOOL CDocManager::DoPromptFileName(CString& fileName, UINT nIDSTitle, DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate)
{
    CFileDialog dlgFile(bOpenFileDialog, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, NULL, NULL, 0);

    CString title;
    VERIFY(title.LoadString(nIDSTitle));

    dlgFile.m_ofn.Flags |= lFlags;

    CString strFilter;
    CString strDefault;
    if (pTemplate != NULL)
    {
        ASSERT_VALID(pTemplate);
        _AfxAppendFilterSuffix(strFilter, dlgFile.m_ofn, pTemplate, &strDefault);
    }
    else
    {
        // do for all doc template
        POSITION pos = m_templateList.GetHeadPosition();
        BOOL bFirst = TRUE;
        while (pos != NULL)
        {
            pTemplate = (CDocTemplate*)m_templateList.GetNext(pos);
            _AfxAppendFilterSuffix(strFilter, dlgFile.m_ofn, pTemplate,
                bFirst ? &strDefault : NULL);
            bFirst = FALSE;
        }
    }

    // append the "*.*" all files filter
    CString allFilter;
    VERIFY(allFilter.LoadString(AFX_IDS_ALLFILTER));
    strFilter += allFilter;
    strFilter += (TCHAR)'';   // next string please
    strFilter += _T("*.*");
    strFilter += (TCHAR)'';   // last string
    dlgFile.m_ofn.nMaxCustFilter++;

    dlgFile.m_ofn.lpstrFilter = strFilter;
    dlgFile.m_ofn.lpstrTitle = title;
    dlgFile.m_ofn.lpstrFile = fileName.GetBuffer(_MAX_PATH);

    INT_PTR nResult = dlgFile.DoModal();
    fileName.ReleaseBuffer();
    return nResult == IDOK;
}
CDocument* CDocManager::OpenDocumentFile(LPCTSTR lpszFileName)
{
    if (lpszFileName == NULL)
    {
        AfxThrowInvalidArgException();
    }
    // find the highest confidence
    POSITION pos = m_templateList.GetHeadPosition();
    CDocTemplate::Confidence bestMatch = CDocTemplate::noAttempt;
    CDocTemplate* pBestTemplate = NULL;
    CDocument* pOpenDocument = NULL;

    TCHAR szPath[_MAX_PATH];
    ASSERT(lstrlen(lpszFileName) < _countof(szPath));
    TCHAR szTemp[_MAX_PATH];
    if (lpszFileName[0] == '"')
        ++lpszFileName;
    Checked::tcsncpy_s(szTemp, _countof(szTemp), lpszFileName, _TRUNCATE);
    LPTSTR lpszLast = _tcsrchr(szTemp, '"');
    if (lpszLast != NULL)
        *lpszLast = 0;
    
    if( AfxFullPath(szPath, szTemp) == FALSE )
    {
        ASSERT(FALSE);
        return NULL; // We won't open the file. MFC requires paths with
                     // length < _MAX_PATH
    }

    TCHAR szLinkName[_MAX_PATH];
    if (AfxResolveShortcut(AfxGetMainWnd(), szPath, szLinkName, _MAX_PATH))
        Checked::tcscpy_s(szPath, _countof(szPath), szLinkName);

    while (pos != NULL)
    {
        CDocTemplate* pTemplate = (CDocTemplate*)m_templateList.GetNext(pos);
        ASSERT_KINDOF(CDocTemplate, pTemplate);

        CDocTemplate::Confidence match;
        ASSERT(pOpenDocument == NULL);
        match = pTemplate->MatchDocType(szPath, pOpenDocument);
        if (match > bestMatch)
        {
            bestMatch = match;
            pBestTemplate = pTemplate;
        }
        if (match == CDocTemplate::yesAlreadyOpen)
            break;      // stop here
    }

    if (pOpenDocument != NULL)
    {
        POSITION posOpenDoc = pOpenDocument->GetFirstViewPosition();
        if (posOpenDoc != NULL)
        {
            CView* pView = pOpenDocument->GetNextView(posOpenDoc); // get first one
            ASSERT_VALID(pView);
            CFrameWnd* pFrame = pView->GetParentFrame();

            if (pFrame == NULL)
                TRACE(traceAppMsg, 0, "Error: Can not find a frame for document to activate.
");
            else
            {
                pFrame->ActivateFrame();

                if (pFrame->GetParent() != NULL)
                {
                    CFrameWnd* pAppFrame;
                    if (pFrame != (pAppFrame = (CFrameWnd*)AfxGetApp()->m_pMainWnd))
                    {
                        ASSERT_KINDOF(CFrameWnd, pAppFrame);
                        pAppFrame->ActivateFrame();
                    }
                }
            }
        }
        else
            TRACE(traceAppMsg, 0, "Error: Can not find a view for document to activate.
");

        return pOpenDocument;
    }

    if (pBestTemplate == NULL)
    {
        AfxMessageBox(AFX_IDP_FAILED_TO_OPEN_DOC);
        return NULL;
    }

    return pBestTemplate->OpenDocumentFile(szPath);
}
CDocument* CSingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName,
    BOOL bMakeVisible)
    // if lpszPathName == NULL => create new file of this type
{
    CDocument* pDocument = NULL;
    CFrameWnd* pFrame = NULL;
    BOOL bCreated = FALSE;      // => doc and frame created
    BOOL bWasModified = FALSE;

    if (m_pOnlyDoc != NULL)
    {
        // already have a document - reinit it    
        pDocument = m_pOnlyDoc;
        if (!pDocument->SaveModified())
            return NULL;        // leave the original one

        pFrame = (CFrameWnd*)AfxGetMainWnd();
        ASSERT(pFrame != NULL);
        ASSERT_KINDOF(CFrameWnd, pFrame);
        ASSERT_VALID(pFrame);
    }
    else
    {
        // create a new document
        pDocument = CreateNewDocument();
        ASSERT(pFrame == NULL);     // will be created below
        bCreated = TRUE;
    }

    if (pDocument == NULL)
    {
        AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);
        return NULL;
    }
    ASSERT(pDocument == m_pOnlyDoc);

    if (pFrame == NULL)
    {
        ASSERT(bCreated);

        // create frame - set as main document frame
        BOOL bAutoDelete = pDocument->m_bAutoDelete;
        pDocument->m_bAutoDelete = FALSE;
                    // don't destroy if something goes wrong
        pFrame = CreateNewFrame(pDocument, NULL);
        pDocument->m_bAutoDelete = bAutoDelete;
        if (pFrame == NULL)
        {
            AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);
            delete pDocument;       // explicit delete on error
            return NULL;
        }
    }

    if (lpszPathName == NULL)
    {
        // create a new document
        SetDefaultTitle(pDocument);

        // avoid creating temporary compound file when starting up invisible
        if (!bMakeVisible)
            pDocument->m_bEmbedded = TRUE;

        if (!pDocument->OnNewDocument())
        {
            // user has been alerted to what failed in OnNewDocument
            TRACE(traceAppMsg, 0, "CDocument::OnNewDocument returned FALSE.
");
            if (bCreated)
                pFrame->DestroyWindow();    // will destroy document
            return NULL;
        }
    }
    else
    {
        CWaitCursor wait;

        // open an existing document
        bWasModified = pDocument->IsModified();
        pDocument->SetModifiedFlag(FALSE);  // not dirty for open

        if (!pDocument->OnOpenDocument(lpszPathName))
        {
            // user has been alerted to what failed in OnOpenDocument
            TRACE(traceAppMsg, 0, "CDocument::OnOpenDocument returned FALSE.
");
            if (bCreated)
            {
                pFrame->DestroyWindow();    // will destroy document
            }
            else if (!pDocument->IsModified())
            {
                // original document is untouched
                pDocument->SetModifiedFlag(bWasModified);
            }
            else
            {
                // we corrupted the original document
                SetDefaultTitle(pDocument);

                if (!pDocument->OnNewDocument())
                {
                    TRACE(traceAppMsg, 0, "Error: OnNewDocument failed after trying "
                        "to open a document - trying to continue.
");
                    // assume we can continue
                }
            }
            return NULL;        // open failed
        }
        pDocument->SetPathName(lpszPathName);
    }

    CWinThread* pThread = AfxGetThread();
    ASSERT(pThread);
    if (bCreated && pThread->m_pMainWnd == NULL)
    {
        // set as main frame (InitialUpdateFrame will show the window)
        pThread->m_pMainWnd = pFrame;
    }
    InitialUpdateFrame(pFrame, pDocument, bMakeVisible);

    return pDocument;
}
BOOL CDocument::OnOpenDocument(LPCTSTR lpszPathName)
{
#ifdef _DEBUG
    if (IsModified())
        TRACE(traceAppMsg, 0, "Warning: OnOpenDocument replaces an unsaved document.
");
#endif

    CFileException fe;
    CFile* pFile = GetFile(lpszPathName,
        CFile::modeRead|CFile::shareDenyWrite, &fe);
    if (pFile == NULL)
    {
        ReportSaveLoadException(lpszPathName, &fe,
            FALSE, AFX_IDP_FAILED_TO_OPEN_DOC);
        return FALSE;
    }

    DeleteContents();
    SetModifiedFlag();  // dirty during de-serialize

    CArchive loadArchive(pFile, CArchive::load | CArchive::bNoFlushOnDelete);
    loadArchive.m_pDocument = this;
    loadArchive.m_bForceFlat = FALSE;
    TRY
    {
        CWaitCursor wait;
        if (pFile->GetLength() != 0)
            Serialize(loadArchive);     // load me
        loadArchive.Close();
        ReleaseFile(pFile, FALSE);
    }
    CATCH_ALL(e)
    {
        ReleaseFile(pFile, TRUE);
        DeleteContents();   // remove failed contents

        TRY
        {
            ReportSaveLoadException(lpszPathName, e,
                FALSE, AFX_IDP_FAILED_TO_OPEN_DOC);
        }
        END_TRY
        DELETE_EXCEPTION(e);
        return FALSE;
    }
    END_CATCH_ALL

    SetModifiedFlag(FALSE);     // start off with unmodified

    return TRUE;
}
void CTestDoc::Serialize(CArchive& ar)
{
    if (ar.IsStoring())
    {
        // TODO: 在此添加存储代码
    }
    else
    {
        // TODO: 在此添加加载代码
    }
}
原文地址:https://www.cnblogs.com/wuyuan2011woaini/p/5485378.html