Dialog for Selecting (and Creating) Folders

Class Purpose

The CPathDialog class lets users select or create a folder. It’s
just a simple extension of SHBrowseForFolder function.

Functions

Class Constructor

CPathDialog::CPathDialog(
 LPCTSTR lpszCaption=NULL,     //Caption of dialog
 LPCTSTR lpszTitle=NULL,       //Prompt of program
 LPCTSTR lpszInitialPath=NULL, //Initial path
 CWnd* pParent=NULL            //Parent of dialog
);

Display Dialog

int CPathDialog::DoModal();

CPathDialog returns the return value of the DoModal function (can
be either IDOK or IDCANCEL).

Ensure Path Exists

int CPathDialog::MakeSurePathExists(
 LPCTSTR lpPath //Path to driectory you want to exist
);

The MakeSurePathExists function ensures that the path presented by the
lpPath argument exists. If it does not exist, the function attempts to create it.

Returns of the fucntion can be:

  • -1: user cancels create the lpPath directory.
  • 0 : lpPath directory exists or was created.
  • 1 : lpPath is invalid.
  • 2 : can not create lpPath directory.

Integrating the CPathDialog into Your Project

  1. Import two files “pathdialog.h” and “pathdialog.cpp” into your project.
  2. Include the header file “pathdialog.h”
  3. Declare an object for CPathDialog class
  4. Invoke DoModal function to show dialog
  5. If user press OK button, get path name user’s entered by using GetPathName function.

Example of Using the CPathDialog Class:


#include “PathDialog.h”
void CTestPathDialogDlg::OnBrowserButton()
{
CString strInitialPath;
CString strYourCaption(_T(“Your caption here…”));
CString strYourTitle(_T(“Your tilte here…”));

m_ctrlPathName.GetWindowText(strInitialPath);

CPathDialog dlg(strYourCaption, strYourTitle, strInitialPath);

if (dlg.DoModal()==IDOK)
{
m_ctrlPathName.SetWindowText(dlg.GetPathName());
}
}

void CTestPathDialogDlg::OnOKButton()
{
CString strPath;
m_ctrlPathName.GetWindowText(strPath);

if(CPathDialog::MakeSurePathExists(strPath)==0)
{
CDialog::OnOK();
}
}

Downloads

Download demo project – 21 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read