保持最近打开的文件列表

7
我希望在我的MFC应用程序上维护一个简单的最近文件列表,显示4个最近使用的文件名。
我一直在尝试使用Eugene Kain的"The MFC Answer Book"中的示例来将字符串编程添加到基于标准Document/View架构的应用程序的最近文件列表中(请参阅"Managing the Recent Files List (MRU)"):(见http://www.nerdbooks.com/isbn/0201185377)
我的应用程序是一个相当轻量级的实用程序,不使用Document/View架构管理数据、文件格式等。我不确定以上示例中使用的原则是否适用于此处。
是否有人有任何关于如何维护在文件菜单中显示并可以存储在文件/注册表设置中的最近文件列表的示例?最重要的是,我缺乏知识和理解正是阻碍了我前进的障碍。
更新:我最近发现这篇CodeProject文章非常有用...(http://www.codeproject.com/KB/dialog/rfldlg.aspx)
2个回答

5
我最近使用MFC完成了这个任务,所以既然您也在使用MFC,可能会有所帮助:

在:

BOOL MyApp::InitInstance()
{
    // Call this member function from within the InitInstance member function to 
    // enable and load the list of most recently used (MRU) files and last preview 
    // state.
    SetRegistryKey("MyApp"); //I think this caused problem with Vista and up if it wasn't there
                                 //, not really sure now since I didn't wrote a comment at the time
    LoadStdProfileSettings();
}

//..

//function called when you save or load a file
void MyApp::addToRecentFileList(boost::filesystem::path const& path)
{
    //use file_string to have your path in windows native format (\ instead of /)
    //or it won't work in the MFC version in vs2010 (error in CRecentFileList::Add at
    //hr = afxGlobalData.ShellCreateItemFromParsingName)
    AddToRecentFileList(path.file_string().c_str());
}

//function called when the user click on a recent file in the menu
boost::filesystem::path MyApp::getRecentFile(int index) const
{
    return std::string((*m_pRecentFileList)[index]);
}

//...

//handler for the menu
BOOL MyFrame::OnCommand(WPARAM wParam, LPARAM lParam)
{
    BOOL answ = TRUE;

    if(wParam >= ID_FILE_MRU_FILE1 && wParam <= ID_FILE_MRU_FILE16)
    {
        int nIndex = wParam - ID_FILE_MRU_FILE1;

        boost::filesystem::path path = getApp()->getRecentFile(nIndex);
        //do something with the recent file, probably load it

        return answ;
    }
}

你只需要确保你的应用程序派生自CWinApp(我使用一个派生自CFrmWnd的类来处理菜单,也许你也这样做?)。

告诉我这是否适用于您。不确定我是否已经准备好了一切。


我最近发现了你提到的其中一两件事情,特别是LoadStdProfileSettings和AddToRecentFileList,它们是必不可少的(+1)。 - AndyUK

5
你可以使用boost循环缓冲算法在程序运行时维护列表,然后每次更新后将其保存到注册表中(应该很简单),并在程序第一次启动时加载它。

为什么循环缓冲算法,一个简单的4个位置的向量或数组就可以完美胜任。为了存储目的而保存到注册表或本地文件。 - RvdK
2
由于boost的循环缓冲区在空间不足时会自动删除插入的第一个元素,因此它被设计用于像最近文件列表之类的应用。如果使用一个只有4个位置的向量,你需要识别最旧的元素并在满时删除它;但是在使用boost时一切都被自动完成了! - Andreas Bonini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接