This code closes the default "blank" document when an existing file is opened in a MFC MDI application (This behaviour can also be seen in Microsoft's Word and Excel).
It works for files opened from File->Open... menu option and files opened from the MRU (most-recently-used) list.
Best of all, it only requires adding one line of code to your application:
#include "CloseUnusedDocs.h" // STEP #1: INCLUDE HEADER FILE
BOOL CYourDoc::OnOpenDocument(LPCTSTR lpszPathName)
{
if (!CDocument::OnOpenDocument(lpszPathName))
return FALSE;
CCloseUnusedDocs::close_unused_documents(this);
return TRUE;
}
The algorithm for the code is : loop through all of the documents (via all of the document-templates) and close the ones that match the criteria of:
- NOT previously saved (
CDocument::GetPathName()
is empty), AND
- NOT Modified (
CDocument::IsModified()
is zero ) AND
- NOT the document we are in the process of opening (the "this" pointer in the code above)
For more information you can look at the code (it's quite short, and fairly well commented).