您的位置:首页 > 其它

VC如何得到一个文件夹的路径

2010-04-25 17:53 281 查看
使用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已经很好用,但稍嫌麻烦,所以我专门将其封装了一下,力求一步到位。

函数封装如下:

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为空字符串("");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: