[MFC]选择目录对话框和选择文件对话框 保存对话框

来源:互联网 发布:算法统宗中的题目 编辑:程序博客网 时间:2024/05/16 22:41

转载来自:http://blog.csdn.net/u012005313/article/details/46639349

在MFC编程中经常会需要用到选择目录和选择文件的界面,以下总结一下本人常用的这两种对话框的生成方法:

选择目录对话框

[cpp] view plain copy
  1. //选择目录按钮  
  2. void CDcPackerDlg::OnBnClickedDecgen()      
  3. {  
  4.     char szPath[MAX_PATH];     //存放选择的目录路径   
  5.     CString str;  
  6.   
  7.     ZeroMemory(szPath, sizeof(szPath));     
  8.   
  9.     BROWSEINFO bi;     
  10.     bi.hwndOwner = m_hWnd;     
  11.     bi.pidlRoot = NULL;     
  12.     bi.pszDisplayName = szPath;     
  13.     bi.lpszTitle = "请选择需要打包的目录:";     
  14.     bi.ulFlags = 0;     
  15.     bi.lpfn = NULL;     
  16.     bi.lParam = 0;     
  17.     bi.iImage = 0;     
  18.     //弹出选择目录对话框  
  19.     LPITEMIDLIST lp = SHBrowseForFolder(&bi);     
  20.   
  21.     if(lp && SHGetPathFromIDList(lp, szPath))     
  22.     {  
  23.         str.Format("选择的目录为 %s",  szPath);  
  24.         AfxMessageBox(str);   
  25.   
  26.           
  27.     }  
  28.     else     
  29.         AfxMessageBox("无效的目录,请重新选择");     
  30. }  

选择文件对话框

[cpp] view plain copy
  1. CString CDcPackerDlg::BootOpenDialog()   //返回选择的文件名称  
  2. {  
  3.     CString strFile = _T("");  
  4.   
  5.     CFileDialog    dlgFile(TRUE, NULL, NULL, OFN_HIDEREADONLY, _T("Describe Files (*.cfg)|*.cfg|All Files (*.*)|*.*||"), NULL);  
  6.   
  7.     if (dlgFile.DoModal())  
  8.     {  
  9.         strFile = dlgFile.GetPathName();  
  10.     }  
  11.   
  12.     return strFile;  
  13. }  
  14.   
  15. //加载文件按钮  
  16. void CDcPackerDlg::OnBnClickedSelectdec()  
  17. {  
  18.     // TODO: Add your control notification handler code here  
  19.     m_strDescPath = "";        //类的成员变量  
  20.   
  21.     //"打开文件"对话框,选择文件,返回其路径  
  22.     m_strDescPath = BootOpenDialog();  
  23.   
  24.       
  25. }  
保存对话框:
  1. void CExample17Dlg::OnBnClickedSaveButton()   
  2. {   
  3.     // TODO: Add your control notification handler code here   
  4.     // 设置过滤器   
  5.     TCHAR szFilter[] = _T("文本文件(*.txt)|*.txt|Word文件(*.doc)|*.doc|所有文件(*.*)|*.*||");   
  6.     // 构造保存文件对话框   
  7.     CFileDialog fileDlg(FALSE, _T("doc"), _T("my"), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter, this);   
  8.     CString strFilePath;   
  9.   
  10.     // 显示保存文件对话框   
  11.     if (IDOK == fileDlg.DoModal())   
  12.     {   
  13.         // 如果点击了文件对话框上的“保存”按钮,则将选择的文件路径显示到编辑框里   
  14.         strFilePath = fileDlg.GetPathName();   
  15.         SetDlgItemText(IDC_SAVE_EDIT, strFilePath);   
  16.     }   
  17. }  
0 0
原创粉丝点击