一,[FILE/CLOSE]的实现过程:
1.CDocument::OnFileClose()
void CDocument::OnFileClose()
{
if (!SaveModified())
return;
OnCloseDocument();
}
2.CDocument::SaveModified()
BOOL CDocument::SaveModified()
{
//内容是否更改,如果没有直接返回
if (!IsModified())
return TRUE;
//获得文档的标题和名字.....
//弹出提示框,告诉用户是否保存
CString prompt;
AfxFormatString1(prompt, AFX_IDP_ASK_TO_SAVE, name);
switch (AfxMessageBox(prompt, MB_YESNOCANCEL, AFX_IDP_ASK_TO_SAVE))
{
case IDCANCEL:
return FALSE; // 取消
case IDYES:
if (!DoFileSave())
return FALSE; // 保存
break;
case IDNO: //不保存
break;
default:
ASSERT(FALSE);
break;
}
return TRUE; // keep going
}
3.CDocument::OnCloseDocument()
void CDocument::OnCloseDocument()
{
BOOL bAutoDelete = m_bAutoDelete;
m_bAutoDelete = FALSE; // don't destroy document while closing views
while (!m_viewList.IsEmpty())
{
// View的外围的Frame
CView* pView = (CView*)m_viewList.GetHead();
ASSERT_VALID(pView);
CFrameWnd* pFrame = pView->EnsureParentFrame();
//关闭Frame,这也将销毁view
PreCloseFrame(pFrame);
pFrame->DestroyWindow();
}
m_bAutoDelete = bAutoDelete;
DeleteContents();
// delete the document if necessary
if (m_bAutoDelete)
delete this;
}
二,[FILE/SAVE]的处理过程
1.CDocument::OnFileSave()
void CDocument::OnFileSave()
{
DoFileSave();
}
2.CDocument::DoFileSave()
BOOL CDocument::DoFileSave()
{
//获得文件属性
DWORD dwAttrib = GetFileAttributes(m_strPathName);
if (dwAttrib & FILE_ATTRIBUTE_READONLY)
{ //没有读写权限或文件不存在
if (!DoSave(NULL))
{
return FALSE;
}
}
else
{ //保存文件
if (!DoSave(m_strPathName))
{
return FALSE;
}
}
return TRUE;
}
3.CDocument::DoSave
BOOL CDocument::DoSave(LPCTSTR lpszPathName, BOOL bReplace)
{
CString newName = lpszPathName;
//如果文件名为空:[FILE/SAVEAS]
if (newName.IsEmpty())
{
//获得文件名
}
//打开文件选择对话框
if (!AfxGetApp()->DoPromptFileName(newName,
bReplace ? AFX_IDS_SAVEFILE : AFX_IDS_SAVEFILECOPY,
OFN_HIDEREADONLY | OFN_PATHMUSTEXIST, FALSE, pTemplate))
return FALSE;
}
//保存文档内容
OnSaveDocument(newName);
return TRUE;
}
4. CDocument::OnSaveDocument
BOOL CDocument::OnSaveDocument(LPCTSTR lpszPathName)
{
//打开文件
CFileException fe;
CFile* pFile = NULL;
pFile = GetFile(lpszPathName, CFile::modeCreate |CFile::modeReadWrite | CFile::shareExclusive, &fe);
CArchive saveArchive(pFile, CArchive::store | CArchive::bNoFlushOnDelete);
saveArchive.m_pDocument = this;
saveArchive.m_bForceFlat = FALSE;
TRY
{
Serialize(saveArchive); // 序列化保存
saveArchive.Close();
ReleaseFile(pFile, FALSE);
}
CATCH_ALL(e)
{
ReleaseFile(pFile, TRUE);
return FALSE;
}
END_CATCH_ALL
SetModifiedFlag(FALSE); // back to unmodified
return TRUE; // success
}
三,[FILE/SAVEAS]的处理过程
void CDocument::OnFileSaveAs()
{
if(!DoSave(NULL))
TRACE(traceAppMsg, 0, "Warning: File save-as failed./n");
}
然后与[FILE/SAVE]处理一样