Click here to Skip to main content
16,018,938 members
Articles / Desktop Programming / MFC
Article

Multiple Selection in a File Dialog

Rate me:
Please Sign up or sign in to vote.
4.94/5 (49 votes)
23 Nov 2002CPOL4 min read 286.6K   5.1K   61   58
Shows how to do multiple file selection in a file dialog without having to worry about the size of the buffers

Introduction

When using the Windows FileOpen dialog with multiple selection do you ever wonder how much memory you have to allocate for the buffer. Is one kilobyte going to be enough? Or should you make it ten? How about one Megabyte just to be safe?

It seems that no matter what you choose, you are either going to waste a whole bunch of memory just to be safe, or your user is going to select a bunch of files only to find their selection didn't work because your buffer was too small.

Well no more. If you use the method I am about to describe your problems will be over.

How To

The first and most important thing is that this method will only work with the Explorer style file dialogs because we make use of various messages that the old windows 3.1 style file dialogs do not support.

When you are browsing through your file system using the file dialog, the dialog will send WM_NOTIFY messages to the OFNHook procedure. ( Note: In MFC the hook procedure is set up automatically when you use the CFileDialog class, look up OPENFILENAME in MSDN if you want more information on setting up the OFNHook procedure if you are not using MFC. ) We are interested in trapping the CDN_SELCHANGE notification message. The CDN_SELCHANGE notification message is sent whenever the selection changes in the list box that displays the currently open folder. In MFC you can handle this message by overriding the CFileDialog::OnFileNameChange() function.

Now, in our CDN_SELCHANGE handler, the first thing that is required is to check if the buffer that was allotted using the OPENFILENAME structure is large enough. If it is, then we do not have to bother duplicating the default behaviour. If however, the buffer is too small then we have to take matters into our own hands.

To figure out the required size of the buffer we send two messages to the file dialog. They are the CDM_GETFOLDERPATH and CDM_GETSPEC messages. The CDM_GETFOLDERPATH message will return the required size of a buffer needed to hold the currently selected folder path, and the CDM_GETSPEC will return the required size of the buffer needed to hold all the file names. Now, just add these two values together and if the sum is greater than the nMaxFile member of the OPENFILENAME structure then the supplied buffer is too small.

Now, in order to retrieve the file names from the file dialog, we will have to set up two buffers of our own. One for the folder path and an other for the files. Use the CDM_GETFOLDERPATH message to fill the folder buffer, and use the CDM_GETSPEC message to fill the files buffer. All the files in the files buffer will be enclosed between quotation marks, and separated by spaces. ( In other words, exactly as they are shown in the "File Name" edit box. ) At this point it is also advisable to set some sort of flag to let us know later that we have used our own buffers, and not the default one.

void CFECFileDialog::OnFileNameChange()
{
    TCHAR dummy_buffer;
    
    // Get the required size for the 'files' buffer
    UINT nfiles = CommDlg_OpenSave_GetSpec(GetParent()->m_hWnd, 
        &dummy_buffer, 1);

    // Get the required size for the 'folder' buffer
    UINT nfolder = CommDlg_OpenSave_GetFolderPath(GetParent()->m_hWnd, 
        &dummy_buffer, 1);

    // Check if lpstrFile and nMaxFile are large enough
    if (nfiles + nfolder > m_ofn.nMaxFile)
    {
        bParsed = FALSE;
        if (Files)
            delete[] Files;
        Files = new TCHAR[nfiles + 1];
        CommDlg_OpenSave_GetSpec(GetParent()->m_hWnd, Files, nfiles);

        if (Folder)
            delete[] Folder;
        Folder = new TCHAR[nfolder + 1];
        CommDlg_OpenSave_GetFolderPath(GetParent()->m_hWnd, Folder, 
            nfolder);
    }
    else if (Files)
    {
        delete[] Files;
        Files = NULL;
        delete[] Folder;
        Folder = NULL;
    }

    CFileDialog::OnFileNameChange();
}

Now, another thing we have to handle is when the user clicks the OK button. When the OK button is clicked, the file dialog will return IDOK if there were no errors, however, in our case there will be an error as the default buffer was too small, so the file dialog will return IDCANCEL. What we have to do now is check the error code using the CommDlgExtendedError() function and check if the error was FNERR_BUFFERTOOSMALL ( defined in cderr.h ). If that was the error, and our flag was set to tell us we have used our own buffer, then all is well with the world and we can get the file names from our own buffer.

int CFECFileDialog::DoModal()
{
    if (Files)
    {
        delete[] Files;
        Files = NULL;
        delete[] Folder;
        Folder = NULL;
    }

    int ret = CFileDialog::DoModal();

    if (ret == IDCANCEL)
    {
        DWORD err = CommDlgExtendedError();
        if (err == FNERR_BUFFERTOOSMALL/*0x3003*/ && Files)
            ret = IDOK;
    }
    return ret;
}

All that is left is to extract the names from the buffers. In the supplied demo, I have overridden the GetStartPosition() and GetNextPathName() CFileDialog member functions in order to make this easier.

Using the CFECFileDialog class

If you want to use the supplied class in your own code, just add the FECFileDialog.h and FECFileDialog.cpp files to your project, and use the CFECFileDialog class the same as you would use the CFileDialog class.

That's it. I hope some of you find this useful, because I really hate to waste your time and mine :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
President
Canada Canada
Father of two, brother of two, child of two.
Spouse to one, uncle to many, friend to lots.
Farmer, carpenter, mechanic, electrician, but definitely not a plumber.
Likes walks with the wife, board games, card games, travel, and camping in the summer.
High school graduate, college drop-out.
Hobby programmer who knows C++ with MFC and the STL.
Has dabbled with BASIC, Pascal, Fortran, COBOL, C#, SQL, ASM, and HTML.
Realized long ago that programming is fun when there is nobody pressuring you with schedules and timelines.

Comments and Discussions

 
GeneralInstant Crash ... VS2010 Pin
RedDk22-Apr-11 12:06
RedDk22-Apr-11 12:06 
GeneralMy vote of 5 Pin
yenner3-Jan-11 16:14
yenner3-Jan-11 16:14 
GeneralProblem with GetPathName() Function Pin
dsiyekd23-Feb-10 21:34
dsiyekd23-Feb-10 21:34 
GeneralCode worked for me Pin
Greg Niswonger16-Feb-10 2:00
Greg Niswonger16-Feb-10 2:00 
GeneralWindows 7 Pin
Galo Vinueza S.6-Apr-09 19:17
Galo Vinueza S.6-Apr-09 19:17 
GeneralRe: Windows 7 Pin
aputic3-Aug-09 9:20
aputic3-Aug-09 9:20 
NewsRe: Windows 7 Bug Pin
ANIL KUMAR SHARMA (INDIA)15-Sep-09 22:19
ANIL KUMAR SHARMA (INDIA)15-Sep-09 22:19 
GeneralRe: Windows 7 [modified] Pin
PJ Arends3-Oct-09 13:48
professionalPJ Arends3-Oct-09 13:48 
GeneralRe: Windows 7 Pin
Bernd Heusing11-Nov-09 4:22
Bernd Heusing11-Nov-09 4:22 
GeneralRe: Windows 7 Pin
sps-itsec468-Jan-10 7:28
sps-itsec468-Jan-10 7:28 
GeneralRe: Windows 7 Pin
Member 107211272-Apr-14 23:17
Member 107211272-Apr-14 23:17 
GeneralRe: Windows 7 Pin
PJ Arends3-Apr-14 9:56
professionalPJ Arends3-Apr-14 9:56 
NewsWindows Template Library now includes CMultiFileDialog Pin
Jim Barry28-Jul-07 5:36
Jim Barry28-Jul-07 5:36 
GeneralOnFileNameOK() warning - return value opposite!!! Pin
Tornacious3-Aug-06 9:12
Tornacious3-Aug-06 9:12 
Generalmicrosoft support says.... Pin
Haroon Sarwar30-Jan-06 2:29
Haroon Sarwar30-Jan-06 2:29 
GeneralRe: microsoft support says.... Pin
PJ Arends30-Jan-06 5:50
professionalPJ Arends30-Jan-06 5:50 
QuestionShortCut (*.lnk) files? Pin
Divya Rathore12-Jan-06 0:09
Divya Rathore12-Jan-06 0:09 
AnswerRe: ShortCut (*.lnk) files? Pin
PJ Arends12-Jan-06 12:00
professionalPJ Arends12-Jan-06 12:00 
Generalexecution of flash file selecting from filedialog in SDI Pin
abhi rawat19-Oct-05 1:07
abhi rawat19-Oct-05 1:07 
GeneralAdding Folder Paths Pin
Member 171940628-Jun-05 0:43
Member 171940628-Jun-05 0:43 
GeneralRe: Adding Folder Paths Pin
PJ Arends28-Jun-05 7:25
professionalPJ Arends28-Jun-05 7:25 
GeneralCommDlg_OpenSave_GetFolderPath can return < 0 Pin
F Braem4-Mar-05 0:56
F Braem4-Mar-05 0:56 
QuestionCan we choose multiple files(including folder at the same level) Pin
Member 119359917-Feb-05 9:38
Member 119359917-Feb-05 9:38 
Generalingenious !!!! Pin
nedo25-Dec-04 6:44
nedo25-Dec-04 6:44 
GeneralGetOpenFileName() Error Pin
Stefan_L_0119-Aug-04 1:26
Stefan_L_0119-Aug-04 1:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.