【问题标题】:How can I set the default file type for a CFileDialog?如何设置 CFileDialog 的默认文件类型?
【发布时间】:2011-01-20 11:34:41
【问题描述】:

我使用CFileDialog 来显示打开文件对话框。我已将过滤器设置如下:

static TCHAR BASED_CODE szFilter[] = _T("Chart Files (*.xlc)|*.xlc|")
                                     _T("Worksheet Files (*.xls)|*.xls|Data Files (*.xlc;*.xls)|")
                                     _T("*.xlc; *.xls|All Files (*.*)|*.*||");

每当我DoModal 对话框时,我都需要将默认文件类型设置为“工作表文件”。我无法弄清楚该怎么做。 MS Paint 是这样做的,当我们打开打开文件对话框时它会选择“所有图片文件”。

请告诉我怎么做。

【问题讨论】:

  • 得到了答案,可以使用 OPENFILENAME 的 nFilterIndex 来设置默认选择的文件类型。

标签: c++ visual-c++ mfc file-type cfiledialog


【解决方案1】:

您正在寻找SetDefExt function 这允许您为打开/保存文件对话框指定默认文件扩展名。请记住,您指定的字符串不应包含句点 (.)。

当然,您也可以在constructor 中指定它。第二个参数是默认扩展名(lpszDefExt)。

【讨论】:

  • 虽然 MFC 对话框的逻辑有些扭曲,但更改默认扩展名并不会相应地选择默认过滤器。请改用 nFilterIndex。
  • nFilterIndex 不是 CFileDialog 的成员
  • @Michael nFilterIndexOPENFILENAME 结构的成员,我相信,它被CFileDialog 暴露。
  • 是的,我根据那个写了stackoverflow.com/a/63054216/1592639 ...
【解决方案2】:

你应该阅读和写作 此代码将在程序运行期间完成这项工作。为了能够在下次运行程序时显示上次使用的选择,您可以将 LastIndex 的值存储在注册表中。

// A dialog box with several filters for various media file types
static int LastIndex = -1;          // Holds the last used filter. You can store it in the Registry to use it during next run.

const TCHAR szFilter[] = _T("Video Files (*.mpg, *.mov, *.mp4)|*.mpg;*.mov;*.mp4|Audio Files (*.wav, *.mp3, *.m4a, *.flac)|*.wav;*.mp3;*.m4a;*.flac|MXF Files (*.mxf)|*.mxf|All Files (*.*)|*.*||");

CFileDialog dlg(TRUE, _T("Select Media File"), NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, szFilter, this);

if(LastIndex != -1) dlg.m_ofn.nFilterIndex = LastIndex; // restore last used index 
                                                        // from last time

if (dlg.DoModal() == IDOK)
{
    LastIndex = dlg.m_ofn.nFilterIndex; // Store last used index for next time
    CString sFilePath = dlg.GetPathName();
}

【讨论】:

    猜你喜欢
    • 2018-10-03
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2022-06-19
    • 2018-01-14
    • 2014-04-13
    • 2014-07-16
    相关资源
    最近更新 更多