Here’s an example of how to browse for a directory starting
from an initial directory. This code will return whatever was returned from the
browsing operation. The ugly thing about it is the use of a global so there are
potential multi-threading issues to be taken into consideration before utilizing
this ugly little piece of sample code.
CString
g_csInitial; // Ugly global variable.
// This is called from the shell browser, hence the need for
// a global variable.
int CALLBACK BrowseCallbackProc( HWND hwnd, UINT uiMsg, LPARAM wParam, LPARAM
lParam)
{
// Switch on why the callback was called.
switch( uiMsg )
{
// Tell the browser where to start
displaying.
// WPARAM is TRUE to indicate a path,
FALSE to indicate a pidl.
case BFFM_INITIALIZED:
{
SendMessage(
hwnd, BFFM_SETSELECTION, TRUE, (LPARAM)(LPCTSTR)g_csInitial );
break;
}
// Set the status window to the
currently selected path.
case BFFM_SELCHANGED:
{
CString cs;
BOOL b =
SHGetPathFromIDList((LPITEMIDLIST) lParam , cs.GetBuffer( _MAX_PATH ) );
cs.ReleaseBuffer();
if ( b )
SendMessage(hwnd,BFFM_SETSTATUSTEXT,0,(LPARAM)(LPCTSTR)cs);
break;
}
default:
{
break;
}
}
return 0;
}
// csGetFolder
//
// This is the entry point for the directory browsing routine.
//
// CString csInitial - defines the initial directory to
// be selected in the directory browse window.
//
// Returns:
//
// If the user browses to and selects a directory then
// that path will be inserted into the returned CString.
// Otherwise, an empty CString is returned.
CString csGetFolder( CString csInitial )
{
CString csReturn = csInitial;
BROWSEINFO bi;
LPITEMIDLIST pidl = 0;
LPMALLOC pMalloc = 0;
do {
// Allocate a structure in memory
space used by the shell.
if (FAILED(SHGetMalloc(&pMalloc)))
break;
// Initialize the structure.
ZeroMemory(&bi,sizeof(bi));
bi.hwndOwner = NULL;
bi.pszDisplayName = 0;
bi.pidlRoot = 0;
bi.lpfn = BrowseCallbackProc;
// Setup to tell the browser where
its initial
// selection should be.
g_csInitial = csInitial;
// Start the browsing operation.
if (!(pidl = SHBrowseForFolder(&bi)))
break;
// Extract the user's selected path
into the
// return CString.
SHGetPathFromIDList( pidl,
csReturn.GetBuffer( _MAX_PATH ) );
csReturn.ReleaseBuffer();
} while (false);
// Clean up.
if ( pidl )
pMalloc->Free(pidl);
if ( pMalloc )
pMalloc->Release();
return csReturn;
}