MFC选择文件(夹)按钮实现

MFC选择文件(夹)按钮实现缓存

选择文件(夹)

 1 void CFileSelectDlg::OnBnClickedButtonSelect()
 2 {
 3     if(((CButton*)(GetDlgItem(IDC_RADIO_FILE)))->GetCheck())
 4     {
 5         char strExt[5] = "dat";//设置文件的读取类型
 6         CString szFilter = "GeoTiff Files (*.dat)|*.dat|All Files (*.*)|*.*||";
 7         SelectFile(strExt,szFilter);
 8     }
 9     else
10     {
11         CString floder = SelectFolder();
12         SetDlgItemText(IDC_EDIT_PATH,floder);
13     }
14 }

选择文件

 1 bool CFileSelectDlg::SelectFile(char* strExt,CString const& szFilter)
 2 {
 3     CFileDialog    dlg(TRUE,strExt,NULL,OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT,szFilter);
 4     dlg.m_ofn.lpstrTitle = "请选择缓存文件";
 5     CString inPath;
 6     CArray<CString,CString> aryFilename;
 7     if(dlg.DoModal() == IDOK)
 8     {
 9         CString filenames;
10         POSITION posFile = dlg.GetStartPosition();
11         while(posFile != NULL)
12         {
13             aryFilename.Add(dlg.GetNextPathName(posFile));
14         }
15     }
16     
17     int SelFileNum = aryFilename.GetSize();
18     if(SelFileNum==0)
19     {
20         AfxMessageBox("没有选择缓存文件");
21         return false;
22     }
23     return true;
24 }

选择文件夹

 1 CString CFileSelectDlg::SelectFolder()
 2 {
 3     TCHAR            szFolderPath[255] = {0};
 4     CString          strFolderPath;
 5     BROWSEINFO       sInfo;
 6     ::ZeroMemory(&sInfo,sizeof(BROWSEINFO));
 7     sInfo.pidlRoot = 0;
 8     sInfo.lpszTitle = "请选择缓存文件所在文件夹";
 9     sInfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_EDITBOX |BIF_DONTGOBELOWDOMAIN;
10     sInfo.lpfn = NULL;
11 
12     LPITEMIDLIST    lpidlBrowse = ::SHBrowseForFolder(&sInfo);
13     if(lpidlBrowse != NULL)
14     {
15         if(::SHGetPathFromIDListA(lpidlBrowse,szFolderPath))
16         {
17             strFolderPath = szFolderPath;
18         }
19     }
20     if(lpidlBrowse != NULL)
21     {
22         ::CoTaskMemFree(lpidlBrowse);
23     }
24     return strFolderPath;    
25 }