Wednesday, December 10, 2008

[VC++] Browse dialog for selecting a folder using SHBrowseForFolder()

If you need to select a folder for some purpose of your application, then you can use the shell function SHBrowseForFolder() to display the browser dialog. For getting the folder path of the selected application use shell function SHGetPathFromIDList().
Please see the below code snippet, you can check and use the same if needed.


BROWSEINFO stBrowseInfo = { 0 };
// Below string will be displayed on the browser dialog
stBrowseInfo.lpszTitle = _T( "Select a directory" );
// Displays a dialog box that enables the user to select a folder
LPITEMIDLIST lpItemIdList = SHBrowseForFolder( &stBrowseInfo );
if( lpItemIdList != 0 )
{
TCHAR tcFolderPath[MAX_PATH];

// Converts the item identifier list to the file system path
if( SHGetPathFromIDList( lpItemIdList, tcFolderPath ) )
{
// Use the folder path obtained

MessageBox(tcFolderPath);
}
// Free the allocated memory
IMalloc *pMalloc = 0;
if( SUCCEEDED( SHGetMalloc ( &pMalloc )) )
{
pMalloc->Free( lpItemIdList );
pMalloc->Release ( );
}
} // If folder selected

On executing the above lines you can have a browser dialog like the one show below

Remember that there are numerous options you can set before calling SHBrowseForFolder() by setting values to the in/out parameter of type LPBROWSEINFO that will qualify the appearance and behaviour of the Browse dialog.

2 comments:

Anonymous said...

Fresh Techie...if you want more flexibility and options like filtering, check boxes, etc and if you want the folder control on your own form, check out FolderView from http://www.ssware.com/fldrview.htm

Anonymous said...

Thanks for sharing.

Jen
www.reviewinfobase.com