【转】MFC打开/保存文件对话框:CFileDialog

CFileDialog


文件选择对话框的使用:首先构造一个对象并提供相应的参数,构造函数原型如下: 
CFileDialog::CFileDialog( BOOL bOpenFileDialog,
LPCTSTR lpszDefExt = NULL,
LPCTSTR lpszFileName = NULL,
DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
 LPCTSTR lpszFilter = NULL,
CWnd* pParentWnd = NULL ,
 DWORD dwSize = 0
);



参数意义如下: 

bOpenFileDialog 为TRUE则显示打开对话框,为FALSE则显示保存对话文件对话框。 
lpszDefExt 指定默认的文件扩展名。 
lpszFileName 指定默认的文件名。 
dwFlags 指明一些特定风格。 
lpszFilter 是最重要的一个参数,它指明可供选择的文件类型和相应的扩展名。参数格式如: 
"Chart Files (*.xlc)|*.xlc|Worksheet Files (*.xls)|*.xls|Data Files (*.xlc;*.xls)|*.xlc; *.xls|All Files (*.*)|*.*||";文件类型说明和扩展名间用 | 分隔,同种类型文件的扩展名间可以用 ; 分割,每种文件类型间用 | 分隔,末尾用 || 指明。 
pParentWnd 为父窗口指针。
dwSize

The size of the OPENFILENAME structure. This value is dependent on the operating system version, so MFC can determine the appropriate kind of dialog box to create (for example, new Windows 2000 dialogs as opposed to NT4 dialogs). The default size of 0 means that the MFC code will determine the proper dialog box size to use based on the operating system version on which the program is run.


创建文件对话框可以使用DoModal(),在返回后可以利用下面的函数得到用户选择: 
CString CFileDialog::GetPathName( ) 得到完整的文件名,包括目录名和扩展名如:c: est est1.txt 
CString CFileDialog::GetFileName( ) 得到完整的文件名,包括扩展名如:test1.txt 
CString CFileDialog::GetExtName( ) 得到完整的文件扩展名,如:txt 
CString CFileDialog::GetFileTitle ( ) 得到完整的文件名,不包括目录名和扩展名如:test1 
POSITION CFileDialog::GetStartPosition( ) 对于选择了多个文件的情况得到第一个文件位置。 
CString CFileDialog::GetNextPathName( POSITION& pos ) 对于选择了多个文件的情况得到下一个文件位置,并同时返回当前文件名。但必须已经调用过POSITION CFileDialog::GetStartPosition( )来得到最初的POSITION变量。 



例如

{
CString 
FilePathName;
CFileDialog dlg(TRUE);///TRUE为OPEN对话框,FALSE为SAVE AS对话框
//dlg.m_ofn.lpstrInitialDir=_T("d:\\"); //这里就设置了对话框的默认目录d盘
if(dlg.DoModal()==IDOK)
FilePathName=dlg.GetPathName();

相关信息:CFileDialog 用于取文件名的几个成员函数:
假如选择的文件是C:WINDOWSTEST.EXE
则:
(1)GetPathName();取文件名全称,包括完整路径。取回C:WINDOWSTEST.EXE
(2)GetFileTitle();取文件全名:TEST.EXE
(3)GetFileName();取回TEST
(4)GetFileExt();取扩展名EXE
 
原文地址:https://www.cnblogs.com/Miami/p/hong_0121.html