ShellBrowseForFolder

Shows a shell BrowseForFolder dialog box with an initial path set.

Archived content: This source code is currently inactive and may be outdated or no longer maintained or functional.

Windows bietet Standarddialoge an, um den Benutzer Dateien oder Verzeichnisse im Dateisystem auswählen zu lassen. Während der Dateidialog sehr bekannt ist (bekommt man ihn doch in jeder Anwendung zum Speichern und Öffnen seiner Dateien zu sehen), ist die Verzeichnisauswahl nicht mehr so verbreitet. Diese Funktion beschreibt, wie man den Dialog verwendet.

Note on the code quality: The content on this page is possibly a bit outdated. I’m not using C++ anymore for quite some time, but I would like to keep the existing and once useful functions available.

Download

ShellBrowseForFolder.cpp1.5 KiBQuelltext der ShellBrowseForFolder-Funktion

Contents of the file ShellBrowseForFolder.cpp:

// Shows a shell BrowseForFolder dialog box with an initial path set.
//
// Gives the ability to customize dialog behaviour within callback function.
//
// Dependencies: CString
//
// Web: http://unclassified.software/source/shellbrowseforfolder

// maybe we need these includes
#include <shlobj.h>
#include <objbase.h>

// callback function for ShellBrowseForFolder
int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM /*lParam*/, LPARAM lpData)
{
    if (uMsg == BFFM_INITIALIZED)
    {
        ::SendMessage(hwnd, BFFM_SETSELECTION, true, lpData);
    }
    return 0;
}

CString ShellBrowseForFolder(CString strTitle, HWND hwndOwner, LPCTSTR szInitPath)
{
    char dest[MAX_PATH];
    char pszPath[255];
    CString str = szInitPath;

    // Check InitPath. It must exist completely if BIF_NEWDIALOGSTYLE is used.
    // InitPath prüfen. Muss vollständig existieren, wenn BIF_NEWDIALOGSTYLE verwendet wird!
    while (!file_exists(str) && !str.IsEmpty())
    {
        str = ShellSplitLast(str);
    }

    BROWSEINFO bi;
    ITEMIDLIST *il;

    bi.hwndOwner = hwndOwner;
    bi.pidlRoot = NULL;
    bi.pszDisplayName = dest;   // Only folder name. Nur Name des Ordners.
    bi.lpszTitle = strTitle;
    bi.ulFlags = BIF_RETURNONLYFSDIRS | 0x40 /*BIF_NEWDIALOGSTYLE @ ShlObj.h*/;
    bi.lpfn = BrowseCallbackProc;
    bi.lParam = (long) str.GetBuffer(0);

    //CoInitialize(0);   // TODO: is this required?
    il = SHBrowseForFolder(&bi);
    SHGetPathFromIDList(il, pszPath);

    return pszPath;
}

// Dependencies:

CString ShellSplitLast(CString strPath)
{
    int pos = strPath.ReverseFind('\\');
    return strPath.Left(pos);
}

Licence and terms of use

This software is freely available as source code and compiled version, without restrictions (“public domain”). There is no warranty, not even for merchantability or fitness for a particular purpose. I am not liable for any damage caused through appropriate or inappropriate use.

Statistic data

  • Created on 2007-04-02.