Select multiple files in CFileDialog

In VC ++ 6.0, MFC, I want to select multiple files

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;
    ...
}

The above code example allows you to select only one file at a time, but I want to select several text files, for example, holding down the control key ( ctrl+ select several files). How can I achieve this?

+3
source share
4 answers

So, in the constructor for CFileDialog, you can set the dwFlags parameter to OFN_ALLOWMULTISELECT. It's just that in order to actually get a few file names back, you need to change the m_ofn.lpstrFile member in CFileDialog to point to the allocated buffer. Look at here:

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; 
}
+8

:

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
}
+3

You must pass the OFN_ALLOWMULTISELECT flag to OpenFileName to allow multiple selection.

+1
source

Insert this line:

opendialog.m_ofn.Flags |= OFN_ALLOWMULTISELECT;

Or set the flag in the CFileDialog constructor, as DeusAduro did.

0
source

Source: https://habr.com/ru/post/1712268/


All Articles