Monday 19 September 2011

MFC File dialog

GUI applications use File dialog to allow user to select file in order to perform some operation on it. MFC offers ready to use CFileDialog class (declared in afxdlgs.h).

It is possible to define a filter for file types that will appear in Files list box. File types are listed in combo box which is located at the bottom of the dialog. Filter is defined with a string made of string couples. First string in a couple is the one that will appear in the dialog's combo box and the second one is the extension itself. All string items are separated with vertical tab and the filter string must end with two vertical tabs.

This code will add two items in file type filter combo box:
 EXE Files (*.exe)
 CAB Files (*.cab)

char pszFilter[] = {"EXE Files (*.exe)|*.exe|CAB Files (*.cab)|*.cab||"};

CFileDialog FileDlg(TRUE, ".exe", NULL, 0, pszFilter);

if(FileDlg.DoModal() == IDOK)
   CString strSelectedFileFullPath(FileDlg.GetPathName());
   CString strSelectedFileName(FileDlg.GetFileName());

If we define filter as:
char pszFilter[] = {"MyApp Setup Files (*.exe;*.cab)|*.exe;*.cab||"};
only exe and cab files will appear in file list box and combo box will have a single item:
   MyApp Setup Files (*.exe;*.cab)

Filter defined as:
char pszFilter[] = {"EXE Files (*.exe)|*.exe|All Files (*.*)|*.*||"};
adds two items to combo box:
   EXE Files (*.exe)
   All Files (*.*)

Two useful methods of this class are:
  • GetPathName() - returns full path to the selected file (including file name)
  • GetFileName() - returns a name of the selected file

CFileDialog allows selecting file either on a local machine or from a shared directory on a network. In the latter case path returned by GetPathName() is a network path (starting with \\remote_host_name\shared_dir\...).

No comments: