How to open Browse for Folder dialog in Visual C++ application?

Some times we may get the requirement in our program to open a dialog to browse for a Folder. CFileDialog is useful to open a dialog for file. It is bit tricky to open a Browse for Folder dialog compare to straight forward CFileDialog class.

Following steps explain how to open a Browse for Folder dialog.

Step (1). We can use SHBrowseForFolder function to open a Browse for Folder dialog. SHBrowseForFolder – It displays a dialog box to allow the user to select a folder.

Step (2). In order to call SHBrowseForFolder function we need to initialize and place the appropriate values in _browseinfo structure.

Step (3). Call SHBrowseForFolder function with initialized  _browseinfo structure. It will open a dialog to select a folder.

Step (4). Once user selected the folder SHBrowseForFolder function returns the PIDL that specifies the location of the folder.

Step (5). Now you can call SHGetPathFromIDList function to get the path from the PIDL. This function returns the folder path.

Step (6). Don’t forget to release the memory assigned to PIDL which is returned by SHBrowseForFolder function.

Following is the example function (BrowseForFolder):

void BrowseForFolder()
{
BROWSEINFO bi = {0};

bi.lpszTitle = _T(“Browse for Folder”);

LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

if ( pidl != NULL )
{
TCHAR tszPath[MAX_PATH] = _T(“\0”);

if ( SHGetPathFromIDList(pidl, tszPath) == TRUE )
{
AfxMessageBox(tszPath);
}

// — Free pidl
CoTaskMemFree(pidl);
}
}

In newer versions of MFC (Microsoft Foundation Classes) libraries, the above process became much easier as simple as opening a CFileDialog. With Visual Studio 2010, introduced a new class CFolderPickerDialog to select a folder.

Following example shows the usage of CFolderPickerDialog class.

void BrowseForFolderEx()
{
CFolderPickerDialog dlgFolder;

if ( dlgFolder.DoModal() == IDOK )
AfxMessageBox(dlgFolder.GetFolderPath());
}

How to open Browse for Folder dialog in Visual C++ application?

2 thoughts on “How to open Browse for Folder dialog in Visual C++ application?

Leave a Reply

Your email address will not be published.

Scroll to top