65.9K
CodeProject 正在变化。 阅读更多。
Home

CMultiDocTemplate的扩展

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (3投票s)

2002 年 8 月 27 日

CPOL
viewsIcon

98793

downloadIcon

1735

一个更真实的文档模板类。

引言

当我们构建并运行一个 MFC MDI 应用程序时,它最初会为我们打开一个新的空文档。然后当我们打开一个现有文档时,它会创建一个新的框架并在该框架中打开文档。但我认为如果它只是替换未修改的空文档并在同一个框架中打开现有文档会更好。因此,我决定从 CMultiDocTemplate 派生一个新的类,并将其命名为 CMultiDocTemplateEx 来完成这些操作。

我只是重载了 OpenDocumentFile(LPCTSTR lpszPathName, BOOL bMakeVisible),在直接调用基类的 OpenDocumentFile() 方法之前。我做了一些测试。如果只有一个文档并且它是未修改的,我会使用 lpszPathName 调用文档的 OnOpenDocument(),并调用它的 SetPathName()。任何其他情况,我们直接调用 CMultiDocTemplate::OpenDocumentFile()。代码非常简单明了。

CDocument* CMultiDocTemplateEx::OpenDocumentFile(LPCTSTR lpszPathName,
                                                    BOOL bMakeVisible)
{
    if (m_docList.GetCount() == 1)
    {
        CDocument* pDocument = (CDocument*)m_docList.GetHead();
        if (pDocument->GetPathName().IsEmpty() && !pDocument->IsModified())
        {
            CWaitCursor wait;
            if (!pDocument->OnOpenDocument(lpszPathName))
            {
                TRACE0("CDocument::OnOpenDocument returned FALSE.\n");
                return NULL;
            }
            pDocument->SetPathName(lpszPathName);
            POSITION pos = pDocument->GetFirstViewPosition();
            CView* pView = pDocument->GetNextView(pos);
            CFrameWnd* pFrame = pView->GetParentFrame();
            InitialUpdateFrame(pFrame, pDocument);
            return pDocument;
        }
    }
    return CMultiDocTemplate::OpenDocumentFile(lpszPathName, bMakeVisible);
}

不知道如何使用它?好的,将 MultiDocTemplateEx.cppMultiDocTemplateEx.h 添加到你的项目中,并在你的 stdafx.h 中包含头文件,如下所示

#include "MultiDocTemplateEx.h"

然后在 InitInstance 中,将 CMultiDocTemplate 更改为 CMultiDocTemplateEx,或者就在该单词后面添加 "Ex",构建、运行、测试它!

© . All rights reserved.