MFC应用之CFileDialog 选择文件路径和文件夹路径

1、选择文件(单个或多个)

bool CMyDlg::OnButtonSelectFile(const CString strDefPath, vector<CString>& vecFileNames)
{
	int nFileType = 0;
	CString strFilter = _T("EXCEL文件(*.xls;*.xlsx)|*.xls;*.xlsx||");
	if (nFileType == 0)
	{
		strFilter = _T("(*.shp)|*.shp||");
	}
	else if (nFileType== 1)
	{
		strFilter = _T("(*.mdb)|*.mdb||");
	}

	bool bRet = false;
	if (nFileType == 0)
	{
		// 需要进行文件多选
		CFileDialog openFileDlg(TRUE, NULL, NULL, OFN_FILEMUSTEXIST |OFN_HIDEREADONLY|OFN_ALLOWMULTISELECT, strFilter);
		DWORD MAXFILE = 2562;   //2562   is   the   max 
		openFileDlg.m_ofn.nMaxFile = MAXFILE; 
		TCHAR* pcFile = new TCHAR[MAXFILE]; 
		openFileDlg.m_ofn.lpstrFile = pcFile; 
		openFileDlg.m_ofn.lpstrFile[0] = NULL; 

		if(openFileDlg.DoModal() == IDOK) 
		{ 
			POSITION pos = openFileDlg.GetStartPosition(); 
			while(pos != NULL) 
			{ 
				CString strFile = openFileDlg.GetNextPathName(pos);
				if (strFile.Trim().IsEmpty())
				{
					continue;
				}
				vecFileNames.push_back(strFile);
			} 
			if (vecFileNames.size() % 2 != 0)
			{
				AfxMessageBox(_T("shp格式必须选择偶数个文件!"));
				bRet = false;
			}
			else
			{
				bRet = true;
			}

		} 
	}
	else
	{
		CFileDialog openFileDlg(TRUE, NULL, NULL, OFN_FILEMUSTEXIST |OFN_HIDEREADONLY, strFilter);
		openFileDlg.m_ofn.lpstrInitialDir = strDefPath;

		if (openFileDlg.DoModal() == IDOK)
		{
			vecFileNames.push_back(openFileDlg.GetPathName());
			bRet = true;
		}
	}

	return bRet;
}

2、选择文件夹

void CTestDlg::OnBnClickedBtnSeldir()
{
	// TODO: 在此添加控件通知处理程序代码
	TCHAR szFolderPath[MAX_PATH] = {0};
	CString strFolderPath;
	BROWSEINFO sInfo;
	ZeroMemory(&sInfo, sizeof(BROWSEINFO));

	sInfo.pidlRoot = 0;
	sInfo.lpszTitle = _T("请选择一个文件夹:");
	sInfo.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_EDITBOX;
	sInfo.lpfn = NULL;

	// 显示文件夹选择对话框
	LPITEMIDLIST lpidlBrowse = SHBrowseForFolder(&sInfo);
	if (lpidlBrowse != NULL)
	{
		// 取得文件夹名
		if (SHGetPathFromIDList(lpidlBrowse,szFolderPath))
		{
			strFolderPath = szFolderPath;
		}
	}
	if(lpidlBrowse != NULL)
	{
		CoTaskMemFree(lpidlBrowse);
	}

	GetDlgItem(IDC_EDIT1)->SetWindowTextW(strFolderPath);
}


CString BrowseDir(const TCHAR* szTitle, const TCHAR* pszInitPath, CWnd* pParent) 
{
	// TODO: Add your control notification handler code here
	CFolderPickerDialog dlg;

	if(szTitle)
	{
		dlg.m_ofn.lpstrTitle = szTitle;
	}

	if(pszInitPath)
	{
		dlg.m_ofn.lpstrInitialDir = pszInitPath;
	}

	if(dlg.DoModal() != IDOK)
	{
		return _T("");
	}

	return dlg.GetPathName();
}

void CProjDlg::OnBnClickedBtnDirpath()
{
	// TODO: 在此添加控件通知处理程序代码
	CString strFolderPath;
	GetDlgItem(IDC_EDIT_DIRPATH)->GetWindowText(strFolderPath);
	strFolderPath.Trim();

	strFolderPath = BrowseDir(_T("请选择一个文件夹:"), strFolderPath, this);
	if(strFolderPath.IsEmpty())
	{
		return;
	}

	GetDlgItem(IDC_EDIT_DIRPATH)->SetWindowText(strFolderPath);
}

你可能感兴趣的:(MFC,mfc,选择文件和文件夹)