First Example:
有时我们需要获得某个文件夹的路径,而不是文件的路径,这时需要用API函数SHBrowseForFolder来实现。
函数原型为:
LPITEMIDLIST SHBrowseForFolder(LPBROWSEINFO lpbi);
其中LPBROWSEINFO为BROWSEINFO结构的指针。
BROWSEINFO结构如下:
typedef struct _browseinfo {
HWND hwndOwner;
LPCITEMIDLIST pidlRoot;
LPSTR pszDisplayName;
LPCSTR lpszTitle;
UINT ulFlags;
BFFCALLBACK lpfn;
LPARAM lParam;
int iImage;
} BROWSEINFO;
调用例子如下:
void CMakemifDlg::OnRecPcpath()
{
CString sFolderPath;
BROWSEINFO bi;
char Buffer[MAX_PATH];
//初始化入口参数bi开始
bi.hwndOwner = NULL;
bi.pidlRoot = NULL;
bi.pszDisplayName = Buffer;//此参数如为NULL则不能显示对话框
bi.lpszTitle = "修改接收路径";
bi.ulFlags = 0;
bi.lpfn = NULL;
bi.iImage=IDI_ICON2;
//初始化入口参数bi结束
LPITEMIDLIST pIDList = SHBrowseForFolder(&bi);//调用显示选择对话框
if(pIDList)
{
SHGetPathFromIDList(pIDList, Buffer);
//取得文件夹路径到Buffer里
sFolderPath = Buffer;//将路径保存在一个CString对象里
}
LPMALLOC lpMalloc;
if(FAILED(SHGetMalloc(&lpMalloc))) return;
//释放内存
lpMalloc->Free(pIDList);
lpMalloc->Release();
}
===================================================================================
Another Example:
VC中没有现成的函数来选择一个文件夹,但这是经常会用到的,怎么办?
自动动手,丰衣足食!
使用SHBrowseForFolder,代码如下:
#include <Shlobj.h>
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();
}