目标:
针对自动生成的“打开”菜单,实现文件过滤,并设置默认打开文件路径。
实现:
建立ID_FILE_OPEN的消息映射函数(假设其名字为OnFileOpen),在此函数中添加如下代码:
CString strCurrentPath;
GetCurrentDirectory(200,strCurrentPath.GetBuffer(200)); //获取当前路径
strCurrentPath.ReleaseBuffer();
CFileDialog fileDlg(TRUE, 0, 0, 4|2,_T("Bitmap Files(*.bmp)|*.bmp||"),0,0); /*_T ("Bitmap Files(*.bmp)|*.bmp||")设置文件过滤器*/
fileDlg.m_ofn.lpstrInitialDir = strCurrentPath; /*设置打开文件对话框中的默认路径*/
fileDlg.DoModal();
ps:实现此功能的关键是CFileDialog中m_ofn成员的使用。文件过滤器也可通过m_ofn来设置。自己定义的打开、保存文件对话框时,也可以通过上述方法修改对话框属性。
打开文件对话框
const char pszFilter[] = _T("EXE File (*.txt)|*.txt|All Files (*.*)|*.*||");
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
pszFilter, this);
dlg.m_ofn.lpstrInitialDir = "c:\\WINDOWS\\"; //设置对话框默认呈现的路径
if(dlg.DoModal() == IDOK)
{
CString strFilePath = dlg.GetPathName();
/*如果有多个文件,则
for(POSITION pos = dlg.GetStartPosition(); pos!=NULL; )
{
CString strFilePathName = dlg.GetNextPathName(pos);
*/
}
保存文件对话框
const char pszFilter[] = _T("EXE Files (*.txt)|*.txt||");
CFileDialog dlgSave( FALSE, //FALSE为保存
_T(".txt"), //自动加上的扩展名
_T("Output.txt"), //默认保存的文件名
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
pszFilter, this);
目录选择对话框
BROWSEINFO bi;
char szPathName[MAX_PATH];
char szTitle[] = "选择路径";
ZeroMemory(&bi, sizeof(BROWSEINFO));
bi.hwndOwner = GetSafeHwnd();
bi.pszDisplayName = szPathName;
bi.lpszTitle = szTitle;
bi.ulFlags = 0x0040 ;
CString str;
CString strDir; //选择的目录
LPITEMIDLIST idl = SHBrowseForFolder(&bi);
if(idl == NULL)
{
strDir= "";
return;
}
SHGetPathFromIDList(idl, str.GetBuffer(MAX_PATH * 2));
str.ReleaseBuffer();
if(str != "" && str.GetAt(str.GetLength() - 1) != '\\')
str += "\\";
strDir = str;
评论