//DirBrowser.h
#pragma once
class CDirBrowser
{
public:
CDirBrowser ( bool fRecent = false, const TCHAR* pszTitle = TEXT( "选择目录" ) );
~CDirBrowser( void );
TCHAR* Show( void );
private:
BOOL m_fRecent;
BROWSEINFO m_bi;
LPITEMIDLIST m_pidl;
LPMALLOC m_pMalloc;
static INT CALLBACK BrowseCallbackProc(HWND hwnd,
UINT uMsg,
LPARAM lp,
LPARAM pData);
};
// DirBrowser.cpp
#include "StdAfx.h"
#include <shlobj.h>
#include "DirBrowser.h"
TCHAR s_szRecent[ MAX_PATH ] = { 0 };
CDirBrowser::
CDirBrowser(
bool fRecent /* = false */,
const TCHAR* pszTitle /* = 选择目录 */
)
{
m_fRecent = fRecent;
memset( ( void* )&m_bi, 0, sizeof( BROWSEINFO ) );
m_pidl = NULL;
m_pMalloc = NULL;
m_bi.hwndOwner = NULL;
m_bi.pszDisplayName = 0;
m_bi.lpszTitle = pszTitle;
m_bi.pidlRoot = 0;
m_bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT;
m_bi.lpfn = fRecent ? BrowseCallbackProc : NULL;
}
CDirBrowser::
~CDirBrowser(
void
)
{
if ( m_pMalloc != NULL ) {
if ( m_pidl != NULL ) {
m_pMalloc->Free( m_pidl );
}
m_pMalloc->Release( );
}
}
INT
CALLBACK
CDirBrowser::
BrowseCallbackProc(HWND hwnd,
UINT uMsg,
LPARAM lp,
LPARAM pData
)
{
if (uMsg == BFFM_INITIALIZED)
{
// WParam is TRUE since you are passing a path.
// It would be FALSE if you were passing a pidl.
SendMessage( hwnd, BFFM_SETSELECTION, TRUE, (LPARAM)s_szRecent );
}
return 0;
}
TCHAR*
CDirBrowser::
Show(
void
)
{
if ( SUCCEEDED( SHGetMalloc( &m_pMalloc ) ) )
{
m_pidl = SHBrowseForFolder( &m_bi );
if ( m_pidl == NULL ) {
return NULL;
}
TCHAR m_szPath[ MAX_PATH ] = { 0 };
SHGetPathFromIDList( m_pidl, m_szPath );
lstrcpy( s_szRecent, m_szPath );
}
return s_szRecent;
}