VC中沒有現成的函數來選擇一個文件夾,但這是經常會用到的,怎么辦?
自動動手,豐衣足食!
使用SHBrowseForFolder,代碼如下:
#include
int SelFolder(HWND hParent, CString &strFolder)
{
strFolder.Empty();
LPMALLOC lpMalloc;
if (::SHGetMalloc(&lpMalloc) != NOERROR) return 0;
char szDisplayName[_MAX_PATH];
char szBuffer[_MAX_PATH];
BROWSEINFO browseInfo;
browseInfo.hwndOwner = hParent;
browseInfo.pidlRoot = NULL; // set root at Desktop
browseInfo.pszDisplayName = szDisplayName;
browseInfo.lpszTitle = "Select a folder";
browseInfo.ulFlags = BIF_RETURNFSANCESTORS|BIF_RETURNONLYFSDIRS;
browseInfo.lpfn = NULL;
browseInfo.lParam = 0;
LPITEMIDLIST lpItemIDList;
if ((lpItemIDList = ::SHBrowseForFolder(&browseInfo)) != NULL)
{
// Get the path of the selected folder from the item ID list.
if (::SHGetPathFromIDList(lpItemIDList, szBuffer))
{
// At this point, szBuffer contains the path the user chose.
if (szBuffer[0] == ´\0´) return 0;
// We have a path in szBuffer! Return it.
strFolder = szBuffer;
return 1;
}
else return 1; // strResult is empty
lpMalloc->Free(lpItemIDList);
lpMalloc->Release();
}
return 1;
}
//////調用:
void CMusic1Dlg::OnOK()
{
// TODO: Add extra validation here
CString str;
HWND m_hWnd = GetSafeHwnd();
SelFolder(m_hWnd,str);
m_list.AddString(str);
// CDialog::OnOK();
}
//------------------------------------------------------------------------------------------------------
//_________________________________________________________________
“選擇文件夾”對話框的封裝
我們經常需要用到“選擇文件夾”對話框,相應的API已經很好用,但稍嫌麻煩,所以我專門將其封裝了一下,力求一步到位。
函數封裝如下:
/*****************************************************************
** 函數名:GetPath
** 輸 入: 無
** 輸 出: CString strPath
** strPath非空, 表示用戶選擇的文件夾路徑
** strPath為空, 表示用戶點擊了“取消”鍵,取消選擇
** 功能描述:顯示“選擇文件夾”對話框,讓用戶選擇文件夾
****************************************************************/
CString GetPath()
{
CString strPath = "";
BROWSEINFO bInfo;
ZeroMemory(&bInfo, sizeof(bInfo));
bInfo.hwndOwner = m_hWnd;
bInfo.lpszTitle = _T("請選擇路徑: ");
bInfo.ulFlags = BIF_RETURNONLYFSDIRS;
LPITEMIDLIST lpDlist; //用來保存返回信息的IDList
lpDlist = SHBrowseForFolder(&bInfo) ; //顯示選擇對話框
if(lpDlist != NULL) //用戶按了確定按鈕
{
TCHAR chPath[255]; //用來存儲路徑的字符串
SHGetPathFromIDList(lpDlist, chPath);//把項目標識列表轉化成字符串
strPath = chPath; //將TCHAR類型的字符串轉換為CString類型的字符串
}
return strPath;
}
調用時只需要用到以下代碼:
CString strPath = GetPath();
則strPath為用戶選擇的文件夾路徑。如果用戶點擊了對話框的取消鍵,則strPath為空字符串("");