Last Modification: August 12, 2000

How is SHBrowseForFolder() used?

Several people have trouble getting to use SHBrowseForFolder(). It is, however, very easy. Here's a short example:


    BROWSEINFO bi = { 0 };
    bi.lpszTitle = _T("Pick a Directory");
    LPITEMIDLIST pidl = SHBrowseForFolder ( &bi );
    if ( pidl != 0 )
    {
        // get the name of the folder
        TCHAR path[MAX_PATH];
        if ( SHGetPathFromIDList ( pidl, path ) )
        {
            _tprintf ( _T("Selected Folder: %s\n"), path );
        }

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

There is, however, one gotcha: SHGetPathFromIDList will fail if the selected item is not part of the filesystem, i.e. when a computer or shell namespace is selected. In these cases, you can do the following to get the object's name:


    BROWSEINFO bi = { 0 };
    TCHAR path[MAX_PATH];
    bi.lpszTitle = _T("Pick a Directory");
    bi.pszDisplayName = path;
    LPITEMIDLIST pidl = SHBrowseForFolder ( &bi );
    if ( pidl != 0 )
    {
        // get the name of the folder
        _tprintf ( _T("Selected Item: %s\n"), path );
        // free memory used
        IMalloc * imalloc = 0;
        if ( SUCCEEDED( SHGetMalloc ( &imalloc )) )
        {
            imalloc->Free ( pidl );
            imalloc->Release ( );
        }
    }

Here are a couple more tricks: