在VC ++ 6.0中,MFC我想选择多个文件
CFileDialog opendialog(true); // opens the dialog for open;
opendialog.m_ofn.lpstrTitle="SELECT FILE"; //selects the file title;
opendialog.m_ofn.lpstrFilter="text files (*.txt)\0*.txt\0"; //selects the filter;
if(opendialog.DoModal()==IDOK) //checks wether ok or cancel button is pressed;
{
srcfilename=opendialog.GetPathName(); //gets the path name;
...
}
上面的代码示例一次只允许选择一个文件,但我想选择多个文本文件,例如按住控制键( ctrl +选择多个文件)。我怎样才能做到这一点?
答案 0 :(得分:9)
因此,在CFileDialog的构造函数中,您可以将dwFlags参数设置为“OFN_ALLOWMULTISELECT”。这是一个简单的部分,要实际获取多个文件名,您必须修改CFileDialog中的m_ofn.lpstrFile成员以指向您已分配的缓冲区。看看这里:
http://msdn.microsoft.com/en-us/library/wh5hz49d(VS.80).aspx
以下是一个使用它的示例,希望评论足够:
void CMainFrame::OnFileOpen()
{
char strFilter[] = { "Rule Profile (*.txt)|*.txt*||" };
CFileDialog FileDlg(TRUE, "txt", NULL, OFN_ALLOWMULTISELECT, strFilter);
CString str;
int nMaxFiles = 256;
int nBufferSz = nMaxFiles*256 + 1;
FileDlg.GetOFN().lpstrFile = str.GetBuffer(nBufferSz);
if( FileDlg.DoModal() == IDOK )
{
// The resulting string should contain first the file path:
int pos = str.Find(' ', 0);
if ( pos == -1 );
//error here
CString FilePath = str.Left(pos);
// Each file name is seperated by a space (old style dialog), by a NULL character (explorer dialog)
while ( (pos = str.Find(' ', pos)) != -1 )
{ // Do stuff with strings
}
}
else
return;
}
答案 1 :(得分:3)
一个例子:
CString sFilter = _T("XXX Files (*.xxx)|*.xxx|All Files (*.*)|*.*||");
CFileDialog my_file_dialog(TRUE, _T("xxx"),NULL,
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT,
sFilter, this);
if ( my_file_dialog.DoModal()!=IDOK )
return;
POSITION pos ( my_file_dialog.GetStartPosition() );
while( pos )
{
CString filename= my_file_dialog.GetNextPathName(pos);
//do something with the filename variable
}
答案 2 :(得分:1)
您应该在OpenFileName结构中传递OFN_ALLOWMULTISELECT标志以允许多选。
答案 3 :(得分:0)
插入此行:
opendialog.m_ofn.Flags |= OFN_ALLOWMULTISELECT;
或者像DeusAduro那样在CFileDialog构造函数中设置标志。