Software & Finance





Visual C++ - SHBrowseForDirect - Open Folder Dialog





It is often necessary to browse for a folder instead of a single file. It is required when there are multiple files needs to be handled under the single directory.

 

The function SHBrowseForFolder would make life easier for this purpose. BROWSEINFO struct would guide on the title for the browse folder dialog. SHGetPathFromIDList function would the return the actual path of the selected folder.

 

I have written the function BrowseFolder which return true, if the user has selected the folder. CString reference result would contain the selected folder by the user.

 

 

bool BrowseFolder(const char *title, CString &result)

{

    BROWSEINFO brwinfo = { 0 };

    brwinfo.lpszTitle = _T("Select Your Source Directory");

    LPITEMIDLIST pitemidl = SHBrowseForFolder ( &brwinfo );

    if ( pitemidl == 0 )

        return false;

 

    // get the full path of the folder

    TCHAR path[MAX_PATH];

    if ( SHGetPathFromIDList ( pitemidl, path ) )

    {

        result = path;

    }

    IMalloc *pMalloc = 0;

    if ( SUCCEEDED( SHGetMalloc ( &pMalloc )) )

    {

        pMalloc->Free ( pitemidl );

        pMalloc->Release ( );

    }

 

    return true;

}