原文链接:http://blog.sina.com.cn/s/blog_4a08244901018g5z.html (原文也是转载的)
MFC编程中经常会需要用到选择目录和选择文件的界面,以下总结一下本人常用的这两种对话框的生成方法:
选择目录对话框
//选择目录按钮
void CDcPackerDlg::OnBnClickedDecgen()
{
char szPath[MAX_PATH]; //存放选择的目录路径
CString
str;
ZeroMemory(szPath, sizeof(szPath));
BROWSEINFO bi;
bi.hwndOwner = m_hWnd;
bi.pidlRoot = NULL;
bi.pszDisplayName = szPath;
bi.lpszTitle = "请选择需要打包的目录:";
bi.ulFlags = 0;
bi.lpfn = NULL;
bi.lParam = 0;
bi.iImage = 0;
//弹出选择目录对话框
LPITEMIDLIST
lp = SHBrowseForFolder(&bi);
if(lp && SHGetPathFromIDList(lp,
szPath))
{
str.Format("选择的目录为
%s", szPath);
AfxMessageBox(str);

}
else
AfxMessageBox("无效的目录,请重新选择");
}
void CBianLiDlg::OnSelectFolder()
{
CString str;
BROWSEINFO bi;
char name[MAX_PATH];
ZeroMemory(&bi,sizeof(BROWSEINFO));
bi.hwndOwner = GetSafeHwnd();
bi.pszDisplayName = name;
bi.lpszTitle = "Select
folder";
//bi.ulFlags
= BIF_USENEWUI;
bi.ulFlags = BIF_RETURNFSANCESTORS;
LPITEMIDLIST idl = SHBrowseForFolder(&bi);
if(idl == NULL)
return;
SHGetPathFromIDList(idl,
str.GetBuffer(MAX_PATH));
str.ReleaseBuffer();
m_root = str;//为对话框中与一编辑框对应的CString型变量,保存并显示选中的路径。
if(str.GetAt(str.GetLength()-1)!='/')
m_root+="/";
UpdateData(FALSE);
}
void CBianLiDlg::FileSearch(CString root)
{ // root
为目录名
CFileFind
ff;
CString FilePath;
if (root.Right(1)!="/")
{
root+="/";
}
root+="*.*";
BOOL res=ff.FindFile(root);
while (res)
{
res=ff.FindNextFile();
FilePath=ff.GetFilePath();
if (ff.IsDirectory() && !ff.IsDots())// 找到的是文件夹
{
FileSearch(FilePath);// 递归
}
else if (!ff.IsDirectory() && !ff.IsDots())// 找到的是文件
{
m_ff+=FilePath;
m_ff+=" ";
}
}
}
多文件选择
CFileDialog Dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT|OFN_ALLOWMULTISELECT);
if(Dlg.DoModal()==IDOK)
{
POSITION pos = Dlg.GetStartPosition();
while(pos)
{
CString szFileName = Dlg.GetNextPathName(pos);
AfxMessageBox(szFileName);
}
}
选择文件对话框
CString
CDcPackerDlg::BootOpenDialog() //返回选择的文件名称
{
CString strFile = _T("");
CFileDialog dlgFile(TRUE, NULL, NULL, OFN_HIDEREADONLY,
_T("Describe Files (*.cfg)|*.cfg|All Files (*.*)|*.*||"),
NULL);
if (dlgFile.DoModal())
{
strFile = dlgFile.GetPathName();
}
return strFile;
}
//加载文件按钮
void CDcPackerDlg::OnBnClickedSelectdec()
{
// TODO:
Add your control notification handler code here
m_strDescPath = ""; //类的成员变量
//"打开文件"对话框,选择文件,返回其路径
m_strDescPath = BootOpenDialog();

}
本文介绍了使用MFC创建选择目录对话框和选择文件对话框的方法,并提供了支持多文件选择的功能实现。此外,还展示了如何通过递归方式遍历指定目录下的所有文件。
590

被折叠的 条评论
为什么被折叠?



