Before Visual Studio 2010 , there was no built in class to support Folder chooser dialog in VC++.
Win32 function SHBrowseForFolder() can be used for this purpose.
Following code snippet shows how we can use it.
void OpenDirectory(std::wstring& selectedDirectory) { BROWSEINFO bi; ZeroMemory(&bi, sizeof(bi)); TCHAR szDisplayName[MAX_PATH]; szDisplayName[0] = ' '; bi.hwndOwner = NULL; bi.pidlRoot = NULL; bi.pszDisplayName = szDisplayName; bi.lpszTitle = _T("Title"); bi.ulFlags = BIF_RETURNONLYFSDIRS; bi.lParam = NULL; bi.iImage = 0; LPITEMIDLIST pidl = SHBrowseForFolder(&bi); TCHAR szPathName[256]; if (NULL != pidl) { BOOL bRet = SHGetPathFromIDList(pidl, szPathName); if (bRet) { selectedDirectory = &szPathName[0]; } } }
Usage
CDialogEx::OnOK(); std::wstring sDir; OpenDirectory(sDir); std::wstring sMessage(L"Directory Selected is: "); sMessage += sDir; AfxMessageBox(sMessage.c_str());
From VS 2010 onward we have the built in class CFolderPickerDialog for folder choose purpose.
following code snipplet shows how we can use it From VS 2010 on wards
void OpenDirectory2(std::wstring& sInitialDirectory, std::wstring& selectedDirectory) { /// <summary> /// CFolderPickerDialog constructor</summary> /// <param name="lpszFolder">Initial folder</param> /// <param name="dwFlags">A combination of one or more flags that allow you to customize the dialog box</param> /// <param name="pParentWnd">A pointer to the file dialog-box object's parent or owner window</param> /// <param name="dwSize">The size of the OPENFILENAME structure</param> //explicit CFolderPickerDialog(LPCTSTR lpszFolder = NULL, DWORD dwFlags = 0, CWnd* pParentWnd = NULL, DWORD dwSize = 0, BOOL fNonFileSystemFolders = FALSE); CFolderPickerDialog FolderSelectDialog(sInitialDirectory.c_str()); if (FolderSelectDialog.DoModal() == IDOK) { CString cBuff = FolderSelectDialog.GetPathName(); selectedDirectory = std::wstring(cBuff); } }
Usage
std::wstring sInitialDirectory(L"c:\\"); OpenDirectory2(sInitialDirectory, sDir); sMessage.clear(); sMessage = L"Directory Selected is: "; sMessage += sDir; AfxMessageBox(sMessage.c_str());