.h文件
#if !defined _THIS_IS_MY_DIRECTORY_SELECT_CLASS_
#define _THIS_IS_MY_DIRECTORY_SELECT_CLASS_
class CFolderPickerDlg
{
public:
CFolderPickerDlg ()
{
m_hParentWnd = NULL;
}
~CFolderPickerDlg ()
{
m_hParentWnd = NULL;
}
void SetParentHwnd(HWND hParent) {m_hParentWnd = hParent;}
// --- In:
// --- Out:
// --- Returns: Full path of the selected folder or empty string if
// none or non-file system folder was selected
// --- Effect : Retrieves the path to selected folder
CString GetFolderPath();
// --- In:
// --- Out:
// --- Returns: dialog title
// --- Effect : Retrieves the dialog title
inline CString GetDialogTitle() const {return m_sTitle;}
// --- In: dialog title
// --- Out:
// --- Returns:
// --- Effect : Set the dialog title
inline void SetDialogTitle(const CString &sTitle) {m_sTitle = sTitle;}
// --- In: root path
// --- Out:
// --- Returns: dialog title
// --- Effect : Set root path when first show
static void SetRootFolder(LPCTSTR lpszRoot)
{
sm_LastSelectDirectory = lpszRoot;
}
private:
HWND m_hParentWnd; //选择文件夹对话框的父窗口是谁
CString m_sTitle; //标题栏文本
static CString sm_LastSelectDirectory; //上次选中的路径
static int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lp, LPARAM pData);
};
#endif
.CPP文件
//
// 选择文件夹的类
// Author: yizhengfu 47596
//
#include "stdafx.h"
#include "FolderPickerDlg.h"
/
CString CFolderPickerDlg::sm_LastSelectDirectory;
/
//
CString CFolderPickerDlg::GetFolderPath()
{
BROWSEINFO bi;
bi.hwndOwner = m_hParentWnd; //对话框的所有者的句柄
bi.pidlRoot = NULL; //用来控制只显示以某个目录为节点的目录树
bi.pszDisplayName = NULL; //存放选中的目录名(不是全路径)
bi.lpszTitle = m_sTitle; //对话框上的提示语
bi.lpfn = BrowseCallbackProc; //对话框的回调函数
bi.lParam = 0; //传给回调函数的参数
bi.iImage = 0; //文件夹图标的ID
bi.ulFlags =
BIF_RETURNONLYFSDIRS | //只允许用户选择本地目录, 否则, 用户可以选择一个网络路径
BIF_STATUSTEXT | //当用户选中一个目录时,调用回掉函数
BIF_DONTGOBELOWDOMAIN | //当用户浏览"Entire Network"时,不允许进入任何域
// BIF_BROWSEINCLUDEFILES | //可以选择文件,而不仅仅是只能选择目录
0;
CString strPath;
LPITEMIDLIST lpItemId = ::SHBrowseForFolder(&bi);
if (lpItemId)
{
::SHGetPathFromIDList(lpItemId, strPath.GetBuffer(MAX_PATH));
::GlobalFree(lpItemId);
strPath.ReleaseBuffer();
}
sm_LastSelectDirectory = strPath; //记住本次选中的目录,供下次一步到位
return strPath;
}
int CALLBACK CFolderPickerDlg::BrowseCallbackProc(HWND hwnd, UINT msg, LPARAM lp, LPARAM pData)
{
pData = pData;
TCHAR buf[MAX_PATH];
switch (msg)
{
case BFFM_INITIALIZED:
// 当对话框完成初始化后,设置起始目录为上次选中的目录
_tcscpy(buf, sm_LastSelectDirectory);
::SendMessage(hwnd, BFFM_SETSELECTION, TRUE, (LPARAM)buf);
break;
case BFFM_SELCHANGED:
// 如果在ulFlags中设置了BIF_STATUSTEXT, 每次选中一个目录,这里都会收到一个消息
if (::SHGetPathFromIDList((LPITEMIDLIST)lp, buf))
{
::SendMessage(hwnd, BFFM_SETSTATUSTEXT, 0, (LPARAM)buf);
}
break;
default:
break;
}
return 0;
}