方法一:操作结构体
void GetFilePath()
{
OPENFILENAME ofn; // 公共对话框结构。
TCHAR szFile[MAX_PATH]; // 保存获取文件名称的缓冲区。
// 初始化选择文件对话框。
ZeroMemory(&ofn, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = NULL;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"All(*.*)\0*.*\0Text(*.txt)\0*.TXT\0\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.hInstance = AfxGetResourceHandle();
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// 显示打开选择文件对话框。
if (GetOpenFileName(&ofn))
{
//显示选择的文件。
MessageBox(szFile, L"弹窗标题", MB_OK);
}
}
方法二:使用CFileDialog封装类
void GetFilePath()
{
CFileDialog dlg(true,_T("(*.txt)"),NULL,OFN_HIDEREADONLY,
_T("文本文件|*.txt;*.csv||"),NULL);
if (dlg.DoModal() == IDOK)
{
strFileName=dlg.GetPathName();
}
else
return;
}
–如何使用CFileDialog多选文件,而且文件名很长?
//---------多选且文件名总长很长的文件选择对话框---------
CFileDialog dlg(true, NULL, NULL, OFN_ALLOWMULTISELECT,
_T("文本文件|*.txt||"), NULL);
TCHAR szLargeBuf[2048] = { L"0" };
memset(szLargeBuf, 0, 2048);
dlg.m_ofn.lpstrFile = szLargeBuf;
#ifdef UNICODE
dlg.m_ofn.nMaxFile = 2048;
#else
dlg.m_ofn.nMaxFile = sizeof (szLargeBuf);
#endif
//---------------------------------------------------
POSITION pathPOS;
pathPOS = dlg.GetStartPosition();
CString long_path;
if (dlg.DoModal() == IDOK)
{
for (int i = 0; pathPOS != NULL; i++)
{
paths[i] = dlg.GetNextPathName(pathPOS);
long_path.Append(paths[i] + L";");
}
}
else
return;
//上面是获取文件名