我应该在哪里用c ++声明一个实例?

时间:2011-10-25 08:28:50

标签: visual-c++ mfc instances cfiledialog

我知道这样一个新手问题,但我似乎无法在网上找到任何答案。基本上我使用CFile对话框,不知道我是否应该将它放在.cpp文件或头文件中。提前谢谢。

CFileDialog( BOOL bOpenFileDialog, 
             LPCTSTR lpszDefExt = NULL, 
             LPCTSTR lpszFileName = NULL, 
             DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, 
             LPCTSTR lpszFilter = NULL, 
             CWnd* pParentWnd = NULL ); 

由ChrisBD编辑

好的,我已将包含添加到我的FileDialogDlg.cpp并添加了代码:

CFileDialog fileDlg( TRUE, 
                     NULL, 
                     NULL, 
                     OFN_ALLOWMULTISELECT | OFN_HIDEREADONLY, 
                     "All Files (.)|*.*||", 
                     this); 

// Initializes m_ofn structure 
fileDlg.m_ofn.lpstrTitle = "My File Dialog"; 

// Call DoModal 
if ( fileDlg.DoModal() == IDOK) 
{ 
    CString szlstfile = fileDlg.GetPathName(); // This is your selected file 
                                               // name with path

    AfxMessageBox("Your file name is :" +szlstfile ); 
} 

我的编译器仍然显示出一堆错误

3 个答案:

答案 0 :(得分:2)

关于“无法从...转换参数5”错误的赌注是您将应用程序编译为Unicode(这是一件好事)。然后,必须在代码中使用支持Unicode的字符串文字来表示字符串参数:

CFileDialog fileDlg( TRUE,  
                     NULL,  
                     NULL,  
                     OFN_ALLOWMULTISELECT | OFN_HIDEREADONLY,  
                     L"All Files (.)|*.*||", // <-- I Added the leading L  
                     this);  

您还可以决定使用TEXT()宏或其_T()快捷方式使其兼容ANSI / Unicode。

CFileDialog fileDlg( TRUE,  
                     NULL,  
                     NULL,  
                     OFN_ALLOWMULTISELECT | OFN_HIDEREADONLY,  
                     _T("All Files (.)|*.*||"), // <-- _T("blah")
                     this);  

答案 1 :(得分:1)

答案是既不 - CFileDialog已经在afxdlgs.h中声明了#include <afxdlgs.h> 类(根据CFileDialog documentation),所以只需:

CFileDialog

然后您可以在代码中使用{{1}}。

答案 2 :(得分:1)

我建议您在本地创建一个新实例,设置其属性,然后以模态方式打开它。例如:

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

   // 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.
      ...
   }