Monday, July 22, 2013

Open a Folder Browser with Create Button in MFC

Below is the code snippet that implements a C++ function to open a folder browser in MFC with a Create Folder button, and return the path to the selected folder.


#include "StdAfx.h"
#include "shlobj.h"

CString CAppUtilManager::BrowseForDirectory() const
{
 int MAX_PATH=256;
 TCHAR display_name[MAX_PATH];
 TCHAR path[MAX_PATH];
    BROWSEINFO bi = { 0 };
    bi.lpszTitle = _T("Select an existing or created folder");
 bi.pszDisplayName=display_name;
 bi.ulFlags |= BIF_NEWDIALOGSTYLE;
    LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

 CString directory_path(_T(""));

    if(pidl != 0)
    {
        // get the name of the folder and put it in path
        SHGetPathFromIDList (pidl, path);

        //Set the current directory to path
        directory_path=path;

        // free memory used
        IMalloc * imalloc = 0;
        if ( SUCCEEDED( SHGetMalloc ( &imalloc )) )
        {
            imalloc->Free ( pidl );
            imalloc->Release ( );
        }
    }

 return directory_path;
}

No comments:

Post a Comment