Search code examples
visual-c++mfcinstancescfiledialog

Where should I declare an instance in c++?


Such a newbie question I know but I can't seem to find any answers online. Basically I am using the CFile Dialog and not sure if I should put it in the .cpp file or the header file. Thanks in advance.

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

edit by ChrisBD

Okay, so I have added the includes to my FileDialogDlg.cpp and added the code:

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 ); 
} 

My compiler is still showing a load of errors


Solution

  • My bet regarding the "cannot convert parameter 5 from ..." error is that you compile your app as Unicode (which is a good thing). You must then use Unicode-aware string literals in your code for string parameters:

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

    You could also decide to make it both ANSI/Unicode compatible using the TEXT() macro or its _T() shortcut.

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