Selecting a default folder with SHBrowseForFolder

Today, there was an article posted on the Code Project website that showed how to use SHBrowseForFolder, and there was a question from a reader in the forum, asking how a default folder can be specified. This is pretty easy to do, and all you need to do is to set the BIF_VALIDATE flag, specify a callback, and in the callback, handle BFFM_INITIALIZED which indicates that the dialog is ready, and then SendMessage a BFFM_SETSELECTION message to the HWND of the dialog. Here’s some commented code that shows how this is done.

int CALLBACK BrowseCallbackProc(HWND hwnd,
    UINT uMsg,LPARAM lParam,LPARAM lpData)
    // Look for BFFM_INITIALIZED
    if(uMsg == BFFM_INITIALIZED)
        SendMessage(hwnd, BFFM_SETSELECTION,
            TRUE,(LPARAM)_T("C:\\Program Files"));
    return 0;

void ShowSHBrowseForFolderDemoDlg()
    BROWSEINFO bi = {0};
    // Make sure BIF_VALIDATE is specified
    bi.lpszTitle = _T("Choose a folder");
    // Set the callback function
    bi.lpfn = BrowseCallbackProc;
    LPITEMIDLIST pIDL = SHBrowseForFolder(&bi);
        // Your code goes here...

6 thoughts on “Selecting a default folder with SHBrowseForFolder

  1. The set-selection message has A and W versions, so if you use BFFM_SETSELECTION,
    the lParam should be a TCHAR string. If you do want to pass a Unicode string,
    use BFFM_SETSELECTIONW explicitly.

  2. Thanks Mike. I fixed it now.
    Stupid MSDN incorrectly says that an Unicode string must be used.
    Maybe they meant Unicode-compliant string.
    The lesson here is that, we should not always believe what MSDN says🙂

  3. In my opinion, you’re wrong about it.
    It is YOUR job to handle Unicode and Non-Unicode path.
    The MSDN strictly says that the path can be specified as Unicode string or a PIDL!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s