c++打开文件夹对话框GetOpenFileName 获取打开文件的filename(String类型)、使用Qt中QFileDialog打开、MFC中CFileDialog打开文件

  • Post author:
  • Post category:其他


使用GetOpenFileName 获取打开文件

#include <Windows.h>

string TCHAR2STRING(TCHAR* str) 
{

//  Function:        TCHAR2STRING
//	Description : TCHAR转string
//	Input : str:待转化的TCHAR* 类型字符串
//	Return : 转化后的string类型字符串
	std::string strstr;
	try
	{
		int iLen = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);

		char* chRtn = new char[iLen * sizeof(char)];

		WideCharToMultiByte(CP_ACP, 0, str, -1, chRtn, iLen, NULL, NULL);

		strstr = chRtn;
	}
	catch (exception e)
	{
	}

	return strstr;
}
String filename;
OPENFILENAME ofn = { 0 };
TCHAR strFileName[MAX_PATH] = { 0 };	//用于接收文件名
ofn.lStructSize = sizeof(OPENFILENAME);	//结构体大小
ofn.hwndOwner = NULL;					//拥有着窗口句柄
ofn.lpstrFilter = TEXT("All\0*.*\0jpg\0*.jpg\0bmp\0*.bmp\0\0");	//设置过滤
ofn.nFilterIndex = 1;	//过滤器索引
ofn.lpstrFile = strFileName;	//接收返回的文件名,注意第一个字符需要为NULL
ofn.nMaxFile = sizeof(strFileName);	//缓冲区长度
ofn.lpstrInitialDir = NULL;			//初始目录为默认
ofn.lpstrTitle = TEXT("打开"); //窗口标题
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY; //文件、目录必须存在,隐藏只读选项
//打开文件对话框
if (GetOpenFileName(&ofn)) 
{
	cout<<"打开成功"<<endl;
	filename = TCHAR2STRING(strFileName);//char转String
	cout << filename << endl;
}
else 
{
	MessageBox(NULL, TEXT("请选择一文件"), NULL, MB_ICONERROR);
}

Qt中QFileDialog打开,添加#include < QFileDialog>

QString filename = QFileDialog::getOpenFileName(this,tr("OpenImage"),".",tr("Image File(*.all *.png *.jpg *.bmp)"));

String filenm = String((const char *)filename.toLocal8Bit());//QString转String

MFC中打开、保存文件

void COpenSaveFileDialogDlg::OnBnClickedButtonOpen()
{
	BOOL isOpen = TRUE;		//是否打开(否则为保存)
	CString defaultDir = L"E:\\FileTest";	//默认打开的文件路径
	CString fileName = L"";			//默认打开的文件名
	CString filter = L"文件 (*.doc; *.ppt; *.xls)|*.doc;*.ppt;*.xls||";	//文件过虑的类型
	CFileDialog openFileDlg(isOpen, defaultDir, fileName, OFN_HIDEREADONLY | OFN_READONLY, filter, NULL);
	openFileDlg.GetOFN().lpstrInitialDir = L"E:\\FileTest\\test.doc";
	INT_PTR result = openFileDlg.DoModal();
	CString filePath = defaultDir + "\\test.doc";
	if (result = = IDOK) {
		filePath = openFileDlg.GetPathName();
	}
	CWnd::SetDlgItemTextW(IDC_EDIT_SRC, filePath);
}

//保存文件
void COpenSaveFileDialogDlg::OnBnClickedButtonSave()
{
	BOOL isOpen = FALSE;		//是否打开(否则为保存)
	CString defaultDir = L"E:\\FileTest";	//默认打开的文件路径
	CString fileName = L"test.doc";			//默认打开的文件名
	CString filter = L"文件 (*.doc; *.ppt; *.xls)|*.doc;*.ppt;*.xls||";	//文件过虑的类型
	CFileDialog openFileDlg(isOpen, defaultDir, fileName, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, filter, NULL);
	openFileDlg.GetOFN().lpstrInitialDir = L"E:\\FileTest\\test.doc";
	INT_PTR result = openFileDlg.DoModal();
	CString filePath = defaultDir + "\\" + fileName;
	if (result = = IDOK) {
		filePath = openFileDlg.GetPathName();
	}
	CWnd::SetDlgItemTextW(IDC_EDIT_DEST, filePath);
}



版权声明:本文为Licyh1725原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。