【问题标题】:Maintaining a recent files list维护最近的文件列表
【发布时间】:2009-12-17 11:51:15
【问题描述】:

我想在我的 MFC 应用程序上维护一个简单的最近文件列表,其中显示 4 个最近使用的文件名。

我一直在玩 Eugene Kain 的“The MFC Answer Book”中的一个示例,它可以以编程方式将字符串添加到基于标准文档/视图架构的应用程序的“最近文件”列表中:(请参阅“管理最近文件列表 ( MRU)") :

http://www.nerdbooks.com/isbn/0201185377

我的应用程序是一个相当轻量级的实用程序,它不使用文档/视图架构来管理数据、文件格式等。我不确定上面示例中使用的相同原则是否适用于此。

是否有任何示例说明他们如何维护显示在“文件”菜单中的最近文件列表,并且可以将其存储在某处的文件/注册表设置中?最重要的是,我缺乏知识和理解力阻碍了我。

更新:我最近发现这篇 CodeProject 文章非常有用...

http://www.codeproject.com/KB/dialog/rfldlg.aspx

【问题讨论】:

    标签: c++ mfc recent-file-list


    【解决方案1】:

    我最近使用 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)。
    【解决方案2】:

    您可以在程序运行时使用boost circular buffer算法维护列表,然后在每次更新时将其保存到注册表(应该是微不足道的),并在程序首次启动时加载。

    【讨论】:

    • 为什么一个循环缓冲区算法,一个简单的向量或 4 个位置的数组就可以解决问题。保存到注册表或本地文件用于存储目的
    • 因为 boost 的循环缓冲区在空间不足时会自动擦除插入的第一个元素。它专为诸如最近的文件列表之类的东西而设计。使用具有 4 个位置的向量,您必须识别最旧的元素并在它已满时将其删除;有了 boost,这一切都是自动完成的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多