MFC 选择一个文件或者文件夹路径

//选择文件
CFileDialog dlg(TRUE, 0, 0, OFN_HIDEREADONLY, "文本文件|*.txt|所有文件|*.*)||",0);
if (dlg.DoModal())
{
 CString filePath=dlg.GetPathName();
 CString fileNameWithNoExt=dlg.GetFileTitle();
}

//选择文件夹版本1

void CMyTestDlg::OnBnClickedButton1()
{
 TCHAR chPath[255]; //用来存储路径的字符串
 CString strPath;
 BROWSEINFO bInfo;
 GetModuleFileName(NULL,chPath,MAX_PATH);
 strPath             =chPath;
 ZeroMemory(&bInfo, sizeof(bInfo));
 bInfo.hwndOwner     = m_hWnd;
 bInfo.lpszTitle     = _T("请选择路径: ");
 bInfo.ulFlags       = BIF_RETURNONLYFSDIRS|BIF_EDITBOX;
 //bInfo.lpfn          = BrowseCallbackProc;
 bInfo.lParam        = (LPARAM)strPath.GetBuffer(strPath.GetLength());
 LPITEMIDLIST lpDlist; //用来保存返回信息的IDList
 lpDlist = SHBrowseForFolder(&bInfo) ; //显示选择对话框
 if(lpDlist != NULL) //用户按了确定按钮
 {
  SHGetPathFromIDList(lpDlist, chPath);//把项目标识列表转化成字符串
  strPath = chPath; //将TCHAR类型的字符串转换为CString类型的字符串
  ((CEdit*)GetDlgItem(IDC_EDIT1))->SetWindowText(strPath);
 }
}

//选择文件夹版本2
bool GetFolder(CString& folderpath, CString lastSelectedDir, const char* szCaption = NULL, HWND hOwner = NULL)
{
 bool retVal = false;
 // The BROWSEINFO struct tells the shell
 // how it should display the dialog.
 BROWSEINFO bi;
 memset(&bi, 0, sizeof(bi));
 bi.ulFlags   = BIF_USENEWUI;
 bi.hwndOwner = hOwner;
 bi.lpszTitle = szCaption;
 bi.lpfn=initSelectedDirProc;
 bi.lParam=(LPARAM)(LPCTSTR)lastSelectedDir;
 // must call this if using BIF_USENEWUI
 ::OleInitialize(NULL);
 // Show the dialog and get the itemIDList for the selected folder.
 LPITEMIDLIST pIDL = ::SHBrowseForFolder(&bi);
 if(pIDL != NULL)
 {
  // Create a buffer to store the path, then get the path.
  char buffer[_MAX_PATH] = {'\0'};
  if(::SHGetPathFromIDList(pIDL, buffer) != 0)
  {
    // Set the string value.
    folderpath = buffer;
    retVal = true;
  } 
  // free the item id list
  CoTaskMemFree(pIDL);
 }
 ::OleUninitialize();
 return retVal;
}

posted @ 2013-12-04 18:04  酷熊  阅读(2163)  评论(0编辑  收藏  举报