2011-03-25 156 views

回答

6

下面是MSDN對打開的對話框的例子:

void CMyClass::OnFileOpen() 
{ 
    // szFilters is a text string that includes two file name filters: 
    // "*.my" for "MyType Files" and "*.*' for "All Files." 
    TCHAR szFilters[]= _T("MyType Files (*.my)|*.my|All Files (*.*)|*.*||"); 

    // Create an Open dialog; the default file name extension is ".my". 
    CFileDialog fileDlg(TRUE, _T("my"), _T("*.my"), 
     OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters); 

    // Display the file dialog. When user clicks OK, fileDlg.DoModal() 
    // returns IDOK. 
    if(fileDlg.DoModal() == IDOK) 
    { 
     CString pathName = fileDlg.GetPathName(); 

     // Implement opening and reading file in here. 

     //Change the window's title to the opened file's title. 
     CString fileName = fileDlg.GetFileTitle(); 

     SetWindowText(fileName); 
    } 
} 

對於另存爲對話框,只需改變由CFileDialog的呼叫:

CFileDialog fileDlg(FALSE, _T("my"), _T("*.my"), 
     OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters); 

備註:

  • 一些參數是可選的。
  • szFilters包含您需要的文件擴展名。
+0

非常感謝 – Naruto 2011-03-25 13:16:51

+1

在另存爲的情況下,不應使用OFN_FILEMUSTEXIST。 OTOH,OFN_OVERWRITEPROMPT很可能是想要的。 – 2013-03-20 10:29:26

1

像這樣:

CFileDialog dlg(FALSE); 
dlg.DoModal(); 
+0

如何在一行中獲取所有文件擴展名? – Naruto 2011-03-25 05:48:10