MFC CFileDialog 在用户最后选择的位置打开 运行

MFC CFileDialog open at location that was selected by user at last run

我有一个 MFC C++ 应用程序,它有一个 CFileDialog。 我调用它的 DoModal 函数来打开文件浏览 window。 我设置了 lp​​strInitialDir,告诉它第一次打开对话框的位置

CString defaultDir = L"C:\tmp\";
CFileDialog d(TRUE);
d.m_ofn.lpstrInitialDir = defaultDir ;

if( d.DoModal ()==IDOK )
    {... app logic after the file was seslected...}

问题是我希望我的程序记住用户的选择。下次用户运行我的应用程序时,我希望我的 DoModal 文件浏览对话框在用户上次使用时选择文件的位置打开。

我该怎么做?

我看到有 LastVisitedMRU 注册表项,但是我找不到任何示例如何正确使用它 CFileDialog.DoModal

非常感谢!

您不需要使用“LastVisitedMRU”来完成此操作。只需使用 CWinApp::GetProfileString and CWinApp::WriteProfileString 方法读取和写入上次访问的文件的路径。例如……

CString defaultDir = AfxGetApp()->GetProfileString(_T(“<registry key>"), _T("LastPath"));

CFileDialog d(TRUE);
d.m_ofn.lpstrInitialDir = defaultDir;
CString selectedPath = _T("");
BOOL rc = FALSE;

if (d.DoModal() == IDOK)
    {
    selectedPath = d.GetPathName();
    rc = AfxGetApp()->WriteProfileString(_T("<registry key>"), _T("LastPath"), selectedPath);
    }

其中,“注册表项”是您在应用程序的 InitInstance 方法中调用 SetRegistry 键时使用的值(如果不是在那里,添加它)。并且,“LastPath”是您想要的任何注册表子项。

注意:示例代码来自 MBCS 项目。