Maintaining Recent File Lists in MFC Applications

A simple application in Visual Studio 2003 that builds on the “MyPad” application provided by Jeff Prosise in Programming Windows with MFC. Alternatively you could probably create the same by running the AppWizard to create a standard view-based application, but making sure to uncheck the Document/View architecture box, as well as the ActiveX Controls box to avoid unnecessary code.

A clone of Windows Notepad to start with, functions such as Undo and Cut are added to allow the implementation of standard Edit menu commands. After installing Jeff’s code I added an Open and Save command to the File menu, with accelerator commands (Ctrl+O, Ctrl+S) as well. In order for this to work some essentials to be included are:

1. A function in the main application to add recent file to the list:

void MyApp::addToRecentFileList( CString path )
{
    AddToRecentFileList( path );
}

2. The member function LoadStdProfileSettings must be called from within the main application’s InitInstance member function in order to enable and load the list of most recently used (MRU) files and the last preview state:

BOOL CMyPadApp::InitInstance()
{
    // Reg. key under which our settings are stored.
    SetRegistryKey(_T("Local AppWizard-Generated Applications") );

    CMainFrame* pFrame = new CMainFrame;
    m_pMainWnd = pFrame;

    // Load std file options, inc. Recent Files list (MRU)
    LoadStdProfileSettings();

    // create and load the frame with its resources
    pFrame->LoadFrame( IDR_MAINFRAME,
                       WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE,
                       NULL,
                       NULL );

    pFrame->ShowWindow( SW_SHOW );
    pFrame->UpdateWindow();

    return TRUE;
}

3. Call an AddToRecentFileList function whenever you save or load a file:

void MyApp::addToRecentFileList( CString path )
{
    AddToRecentFileList( path );
}

4. A function that is called when the user clicks on a recent file on the menu:

BOOL CMainFrame::OnCommand( WPARAM wParam, LPARAM lparam )

{
    // Recent files
    if( wParam <= ID_FILE_MRU_FILE1 &&
        wParam <= ID_FILE_MRU_FILE16 )
    {
        int nIndex = wParam - ID_FILE_MRU_FILE1;
        CMyPadApp* pApp = (CMyPadApp*) AfxGetApp();
        CString path = pApp->getRecentFile( nIndex );

        // Load the recent file
        m_wndView.OnRecentFileOpen( path );
    }
    // Create a new file
    else if ( wParam == ID_FILE_NEW )
    {
        m_wndView.OnFileNew();
    }
    // Open a file
    else if ( wParam == ID_FILE_OPEN )
    {
        m_wndView.OnFileOpen();
    }
    // Save a file
    else if ( wParam == ID_FILE_SAVE )
    {
        m_wndView.OnFileSave();
    }     

    return TRUE;
}
CString MyApp::getRecentFile( int index ) const
{
    return (*m_pRecentFileList)[ index ];
}

Download Visual Studio 2003 project from here.

`