如何在关闭应用程序时自动保存文档到指定名称的文件

13如何在关闭应用程序时自动保存文档到指定名称的文件

当按下应用程序框架上右上角的关闭按钮(带小叉的按钮)时,将引发框架窗口的关闭消息,从而将调用框架类的CFrameWnd::OnClose()函数。

void CFrameWnd::OnClose()

{

   if (m_lpfnCloseProc != NULL && !(*m_lpfnCloseProc)(this))

        return;
 
    // Note: only queries the active document
    CDocument* pDocument = GetActiveDocument();

    if (pDocument != NULL && !pDocument->CanCloseFrame(this))

    {

        // document can't close right now -- don't close it

        return;
    }

    // ... ...

}
在得到当前的活动文档后,就调用文档类的CanCloseFrame(pFrame)函数。而这个函数继续调用基类的CDocument::CanCloseFrame(pFrame)函数。在这个函数里面最终调用CDocument:: SaveModified()函数。让我们仔细看看它的代码。

BOOL CDocument::SaveModified()

{
    if (!IsModified()) //如果文档没有被修改过则不保存

        return TRUE;        // ok to continue

 
    // get name/title of document
    CString name;
    if (m_strPathName.IsEmpty())
    {// m_strPathName是当前文档的路径(包括文件名)。因为在打开应用程序的时候就已经打开了一个叫做machine.mi的文件,所以它不是空字串。
        // get name based on caption
        name = m_strTitle;
        if (name.IsEmpty())
            VERIFY(name.LoadString(AFX_IDS_UNTITLED));
    }
    else
    {

        // get name based on file title of path name

        name = m_strPathName;
        if (afxData.bMarked4)
        {
            AfxGetFileTitle(m_strPathName,
 name.GetBuffer(_MAX_PATH), _MAX_PATH);
            name.ReleaseBuffer();
        }
    }
 
    CString prompt;

    AfxFormatString1(prompt, AFX_IDP_ASK_TO_SAVE, name);

    switch (AfxMessageBox(prompt, MB_YESNOCANCEL, AFX_IDP_ASK_TO_SAVE))

    {//如果文档被修改过,则此时弹出一个对话框来询问是否保存。
    case IDCANCEL:

        return FALSE;       // don't continue

 
    case IDYES:

        // If so, either Save or Update, as appropriate

        if (!DoFileSave())

            return FALSE;       // don't continue

        break;
 
    case IDNO:

        // If not saving changes, revert the document

        break;
 
    default:
        ASSERT(FALSE);
        break;
    }
    return TRUE;    // keep going
}
从上面的代码可以看到,如果要作到关闭应用程序时自动地保存修改过的文档,则必须在进入CDocument::SaveModified()之前就消除修改标记。但是如果消除了修改标记文档又不会被存储,所以必须在消除修改标记之前保存文档。保存文档的函数将能够自动地消除修改标记。在哪里进行这个工作好呢?在文档类的CanCloseFrame()函数中。可以在这个函数中调用文档类的OnSaveDocument(lpszPathName)函数。调用这个函数需要给出文件路径和文件名称。

BOOL CMachineDoc::CanCloseFrame(CFrameWnd* pFrame)

{
    if(IsModified()){
        CFile outfile;

        outfile.Open("machine.mi", CFile::modeCreate|CFile::modeReadWrite);

        CString strPath = outfile.GetFilePath();

        outfile.Close();

        OnSaveDocument(strPath); // 这个函数能自动地消除文档修改标记

    }
    return CDocument::CanCloseFrame(pFrame);
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值