スポンサーリンク

CFileDialogのファイル形式のフィルタの指定について

CFileDialogのフィルタ指定の書式は、コンストラクタ指定の場合は "表示用文字列|*.拡張子|"、m_ofn.lpstrFilter指定の場合、"表示用文字列\0*.拡張子\0"となる。

ただし注意があり、m_ofn.lpstrFilterで指定する場合、CStringを使ってはいけない。たぶん、\0が見つかるとそこで文字が切られてしまうため、最初の一つしか選択肢に出てこない。

拡張子の指定方法

以下指定例。プロジェクトはマルチバイト文字セットに設定してある。

m_ofn.lpstrFilter指定

  CFileDialog fileDialog(FALSE, "*.bmp", "output.bmp");
  const char* filter =
    "BMPファイル\0*.bmp\0"
    "JPGファイル\0*.jpg\0"
    "PNGファイル\0*.png\0"
    "全てのファイル\0*.*\0\0";
  fileDialog.m_ofn.lpstrFilter = filter;
  fileDialog.DoModal();

コンストラクタ指定

  CFileDialog fileDialog(
    FALSE, "*.bmp", "output.bmp", 
    OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
    "BMPファイル|*.bmp|"
    "JPGファイル|*.jpg|"
    "PNGファイル|*.png|"
    "全てのファイル|*.*||"
    );
  fileDialog.DoModal();

CStringを使う場合の注意

CStringは\0を含められない(?)ので、m_ofn.lpstrFilterに与える文字列をCStringにしてはいけない。

m_ofn.lpstrFilter指定

  CFileDialog fileDialog(FALSE, "*.bmp", "output.bmp");

  // これは失敗する。
  CString filter =
    "BMPファイル\0*.bmp\0"
    "JPGファイル\0*.jpg\0"
    "PNGファイル\0*.png\0"
    "全てのファイル\0*.*\0\0";

  fileDialog.m_ofn.lpstrFilter = (LPCTSTR)filter;
  fileDialog.DoModal();

コンストラクタ指定

  CFileDialog fileDialog(
    FALSE, "*.bmp", "output.bmp", 
    OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
    // これは成功する
    (LPCTSTR)CString(
      "BMPファイル|*.bmp|"
      "JPGファイル|*.jpg|"
      "PNGファイル|*.png|"
      "全てのファイル|*.*||"
    )
    );
  fileDialog.DoModal();

指定した拡張子を判別

指定した拡張子は、上から1スタートで番号が振られている。

  fileDialog(FALSE, "bmp", "output.bmp");

  const char* filter =
    "BMPファイル\0*.bmp\0"     // index == 1
    "JPGファイル\0*.jpg\0"     // index == 2
    "PNGファイル\0*.png\0"     // index == 3
    "全てのファイル\0*.*\0\0";

  fileDialog.m_ofn.lpstrFilter = (LPCTSTR)filter;

  if (fileDialog.DoModal() == IDOK) {

    // 選択されたファイルのインデックスを取得
    int filterIndex = fileDialog.m_ofn.nFilterIndex;

    switch (filterIndex) {
    case 1:
      MessageBoxA("BMP");
      break;
    case 2:
      MessageBoxA("JPG");
      break;
    case 3:
      MessageBoxA("PNG");
      break;
    case 4:
      MessageBoxA("*.*");
      break;

    }
    
    // なお入力されたファイル名
    CString filePath = fileDialog.GetPathName();
    MessageBoxA(filePath);
  }

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)


この記事のトラックバックURL: