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已经很好用,但稍嫌麻烦,所以我专门将其封装了一下,力求一步到位。

函数封装如下:

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为空字符串("");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值