65.9K
CodeProject is changing. Read more.
Home

Adding Most Recently Used (MRU) Files to an SDI/MDI Application

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.65/5 (9 votes)

Mar 27, 2003

viewsIcon

80363

downloadIcon

1900

Adding Most Recently Used (MRU) files to an SDI/MDI application tutorial.

Sample Image - most_recent_used.gif

Introduction

The Most Recently Used (MRU) files list is standard feature of most Windows applications. This article describes how to add (MRU) support to Windows (SDI/MDI) application using the class CRecentFileList. CRecentFileList is a CObject class that supports control of the most recently used (MRU) file list. Files can be added to or deleted from the MRU file list, the file list can be read from or written to the registry or an .INI file, and the menu displaying the MRU file list can be updated.

Using the code

Adding MRU to MFC SDI or MDI is actually not very difficult. I just add AddToRecentFileList(LPCTSTR lpszPathName) to CDocument derived class which calls the add the path name to CWinApp's CRecentFileList (m_pRecentFileList). I use SDI for this demo.

1. Iinclude afxadv.h to stdafx.h. This contains the class CRecentFileList.

#include <afxadv.h>

2. Add AddToRecentFileList to CDocument derived class and use this function during opening and saving the document.

void CCMRUTestDoc::AddToRecentFileList(LPCTSTR lpszPathName)
{
    ((CCMRUTestApp*)AfxGetApp())->AddToRecentFileList(lpszPathName);
}

BOOL CCMRUTestDoc::OnOpenDocument(LPCTSTR lpszPathName) 
{
    if (!CDocument::OnOpenDocument(lpszPathName))
        return FALSE;
    
    // Add to MRU file list
    AddToRecentFileList(lpszPathName);
    
    return TRUE;
}

BOOL CCMRUTestDoc::OnSaveDocument(LPCTSTR lpszPathName) 
{
    // Add to MRU file list
    AddToRecentFileList(lpszPathName);
    
    return CDocument::OnSaveDocument(lpszPathName);
}

3 Add AddToRecentFileList for CWinApp derived class.

void CCMRUTestApp::AddToRecentFileList(LPCTSTR lpszPathName)
{
    // lpszPathName will be added to the top of the MRU list. 
    // If lpszPathName already exists in the MRU list, it will be moved to the top
    if (m_pRecentFileList != NULL)    {
        m_pRecentFileList->Add(lpszPathName);
    }
}