Click here to Skip to main content
15,867,330 members
Articles / Desktop Programming / MFC
Article

Enhanced CListCtrl that accepts and filters dropped files and folders

Rate me:
Please Sign up or sign in to vote.
5.00/5 (20 votes)
6 Feb 2000 250.2K   3K   89   40
This article explains how to support file drag and drop in your CWnd-derived object

Demo project


Overview
How do I use it in my project?
How does it work?
Acknowledgements


Overview

CFileDropListCtrl - a class derived from CListCtrl that accepts files and/or folders dropped from Explorer.

  • Filters file types based on their extension
  • Resolves shortcuts
  • Checks for duplicate items
  • Allows custom processing of dropped items through an optional user callback function

It was developed to overcome the usability problems of CFileDialog for multiple file selection, and help cater for more experienced users.

I was using CFileDialog to select files to add to a list control. This was OK, but selecting multiple files from different folders is often tedious with the small size of CFileDialog on NT and 95 (it can be resized on 98 & 2000). Its a lot easier to locate files with Windows Explorer and drag and drop them onto the list control. There are less steps required for the user and its more intuitive for experienced ones.

The class has been tested with UNICODE, compiles cleanly on warning level 4 and is const correct.

How do I use it in my project?

You can quickly add this to new or existing projects by substituting it for your original CListCtrl and specifying the type of dropped items you want to accept.

By default, the list inserts the items itself - CListCtrl::InsertItem(0, csFilename) is called for each one. This will work with any style of list you have (Small Icon, Large Icon, List, Report). Note that if you've associated an image list, the default image (index 0) will be used and in Report view, the filename will be inserted into the first column.

If you want to do something fancier, say having a few columns in report view and showing the size and attributes of each file, you can! Give the control a callback function and it will notify you each time a suitable file is dropped - its then up to you to insert it, see below for details.

CFileDropListCtrl has two public members used to update and retrieve settings:

BOOL SetDropMode(const CFileDropListCtrl::DROPLISTMODE& dropMode)
DROPLISTMODE GetDropMode() const

struct DROPLISTMODE
{
    UINT iMask;
    CString csFileExt;
    LPFN_DROP_FILES_CALLBACK pfnCallback;
};
iMask: specifies what type of items to accept - a combination of these flags
FileDropListCtrl::DL_ACCEPT_FILESallow files to be dropped
CFileDropListCtrl::DL_ACCEPT_FOLDERSallow folders to be droppped
CFileDropListCtrl::DL_FILTER_EXTENSIONonly accept files with the specified extension. Specify in csFileExt
CFileDropListCtrl::DL_USE_CALLBACKreceive a callback for each item dropped, specified in pfnCallback (you have responsibility for inserting items into the list)
CFileDropListCtrl::DL_ALLOW_DUPLICATESaccept pathnames even if they already in the list (ignored if you are handling insertion through a callback function)

csFileExt: the file extension on which to filter. Use the format ".extension". Ignored unless DL_FILTER_EXTENSION is specified.

pfnCallback: address of your callback function. Ignored unless DL_USE_CALLBACK is specified.
See step 5 below for detailed info on the format of the callback and how to use it.

SetDropMode() return Values:
- TRUE if the mode was changed successfully
- FALSE if the mode is invalid (specifying DL_USE_CALLBACK, but not populating pfnCallback). The default settings will be used (accept files and folders with no duplicates)


Thats the interface, now step-by-step instructions on how to add and use it in your project:

  1. In resource editor, add a list control to your dialog and check the "Accept Files" property (on the Extended styles page).

    Set the list style to "List", unless you are using a callback function to insert items yourself. Remember that if you choose a "Report" style, you MUST insert one column before any items will be inserted.

  2. Use classwizard to assign a CListCtrl member variable to your list, e.g. m_List.
  3. Now in the header file of your dialog class:
    #include "FileDropListCtrl.h"

    And change the member variable type of your list from CListCtrl to CFileDropListCtrl
    i.e. CFileDropListCtrl m_List;

  4. Now you can specify what kind of items you want the list control to accept. In this case, its best to put it in your dialog class' OnInitDialog():
    CFileDropListCtrl::DROPLISTMODE dropMode;
    
    dropMode.iMask = CFileDropListCtrl::DL_ACCEPT_FILES | 
                          CFileDropListCtrl::DL_FILTER_EXTENSION;
    dropMode.csFileExt = _T(".txt");
    
    m_List.SetDropMode(dropMode);

    this will set the list to only accept files with an extension of ".txt".
    Note: The default mode is to accept all types of files and folders, but not to allow duplicate entries.

  5. Optionally specify a callback function. Without this, the control will take care of inserting items into the list, albeit simply.

    If you want to do something fancier you should install a callback - the control will use this to notify you each time a suitable file is dropped - its then up to you to insert it.

    Declare the callback as a static member function in your dialog class or as a global if you like:

    static HRESULT CALLBACK OnListFileDropped(CListCtrl* pList,
                                              const CString& csPathname,
                                              const UINT& iPathType    );
    pListpointer to the list control the item was dropped onto
    csPathnamefully qualified path of the item
    iPathTypeindicates the type of item.
    CFileDropListCtrl::DL_FOLDER_TYPE or
    CFileDropListCtrl::DL_FILE_TYPE

    In OnInitDialog(), register the callback along with other info - similar to step 4.

    dropMode.iMask |= CFileDropListCtrl::DL_USE_CALLBACK;
    dropMode.pfnCallback = CMyDialog::OnListFileDropped;

    Heres an example of how you might customise insertion by displaying the size of a dropped file:

    HRESULT CMyDialog::OnListFileDropped(CListCtrl* pList,
                                         const CString& csPathname,
                                         const UINT& iPathType    );
    {
        // Only do this for files.
        if(CFileDropListCtrl::DL_FILE_TYPE == iPathType)
        {
            // Get its size
            // returns DWORD in reality
            csFileSize = GetFileSize(csPathname); 
    
            // Insert the filename in column 1
            int nItem = pList->InsertItem(0, csPathname, IMAGE_INDEX);
    
            // And the size in column 2
            pList->SetItemText(nitem, 1, csFileSize);
        }
        return S_OK;
    }
  6. Thats all the code done. Now add the input library "shlwapi.lib" to your projects Link settings. This is for PathFindExtension(), one of many useful Shell Utility functions.
  7. Sorted, drag 'n' drop!...

How does it work?

The method used to handle dropped files is generic and can be applied to any CWnd derived object (e.g. a CEdit). You just need to handle and override 2 messages - WM_CREATE and WM_DROPFILES:
  1. CWnd::OnCreate() - call DragAcceptFiles(TRUE) to register dynamically created windows as drop targets
  2. CWnd::OnDropFiles() to process the files:

As an example, heres how you could handle WM_DROPFILES in a subclassed CEdit control:

void CMyEdit::OnDropFiles(HDROP dropInfo)
{
    //
    // Get the number of pathnames (files or folders) dropped
    //
    UINT nNumFilesDropped = DragQueryFile(dropInfo, 0xFFFFFFFF, NULL, 0);

    //
    // Iterate through them and do some funky stuff
    //
    TCHAR szFilename[MAX_PATH + 1];
    for (UINT nFile = 0 ; nFile < nNumFilesDropped; nFile++)
    {
        //
        // Get the pathname
        //
        DragQueryFile(dropInfo, nFile, szFilename, MAX_PATH + 1);

        //
        // Do something with it...pretty useless, but only example
        //
        CString csText;
        GetWindowText(csText);
        SetWindowText(csText + _T("; ") + szFilename);
    }

    //
    // Windows allocates the memory for file information,
    // so we must clean it up
    //
    DragFinish(dropInfo);
}
Also, you'll probably want to expand any dropped shortcuts before processing the filename, so take a look at CFileDropListCtrl::ExpandShortcut(). It uses the COM interface IShellLink for resolving them.

Acknowledgements

Thanks to these blokes for helping me get this working in double quick time!

  • Handling of droppped files adapted from CDropEdit, 1997 Chris Losinger
  • Shortcut expansion code adapted from CShortcut, 1996 Rob Warner

I'd appreciate a mail if you've any comments, suggestions, or bugs ;-)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseThank you.. just need it.. Pin
yedemon28-Aug-16 2:23
yedemon28-Aug-16 2:23 
Generalmore than 5 stars Pin
k7772-Jan-11 7:55
k7772-Jan-11 7:55 
GeneralPlease Help Pin
Pasha R12-Sep-05 19:42
Pasha R12-Sep-05 19:42 
GeneralA simple Group Box can make you mad !!! Pin
sps-itsec469-Jan-05 6:11
sps-itsec469-Jan-05 6:11 
GeneralRe: A simple Group Box can make you mad !!! Pin
sps-itsec469-Jan-05 10:58
sps-itsec469-Jan-05 10:58 
GeneralRe: A simple Group Box can make you mad !!! Pin
Anup Ashok Kulkarni21-Nov-07 20:57
Anup Ashok Kulkarni21-Nov-07 20:57 
GeneralInstead of adding CListCtrl if add custom control Pin
cool_jay15-Dec-04 2:43
cool_jay15-Dec-04 2:43 
GeneralRe: Instead of adding CListCtrl if add custom control Pin
Stuart Carter20-Dec-04 1:10
Stuart Carter20-Dec-04 1:10 
GeneralList View Pin
HatemElbehairy18-Jun-04 21:52
HatemElbehairy18-Jun-04 21:52 
GeneralRe: List View Pin
Stuart Carter24-Jun-04 0:38
Stuart Carter24-Jun-04 0:38 
GeneralThank you! Pin
Hosam Aly Mahmoud24-Aug-03 22:31
Hosam Aly Mahmoud24-Aug-03 22:31 
GeneralProblem with CPropertyPage Pin
pma7-Jul-03 6:38
pma7-Jul-03 6:38 
GeneralRe: Problem with CPropertyPage Pin
Stuart Carter8-Jul-03 2:25
Stuart Carter8-Jul-03 2:25 
GeneralRe: Problem with CPropertyPage Pin
pma9-Jul-03 6:46
pma9-Jul-03 6:46 
GeneralRe: Problem with CPropertyPage Pin
Stuart Carter10-Jul-03 6:54
Stuart Carter10-Jul-03 6:54 
GeneralRe: Problem with CPropertyPage Pin
pma10-Jul-03 8:14
pma10-Jul-03 8:14 
GeneralRe: Problem with CPropertyPage Pin
Stuart Carter11-Jul-03 0:21
Stuart Carter11-Jul-03 0:21 
GeneralPlease Help Pin
BoscoW21-Feb-03 11:15
BoscoW21-Feb-03 11:15 
GeneralRe: Please Help Pin
Stuart Carter25-Feb-03 0:28
Stuart Carter25-Feb-03 0:28 
GeneralRe: Please Help Pin
BoscoW12-Mar-03 2:00
BoscoW12-Mar-03 2:00 
GeneralRe: Please Help Pin
Stuart Carter17-Mar-03 4:48
Stuart Carter17-Mar-03 4:48 
GeneralGetting the drop-index... small enhancement. Pin
philippe dykmans21-Oct-02 11:21
philippe dykmans21-Oct-02 11:21 
GeneralRe: Getting the drop-index... small enhancement. Pin
Stuart Carter27-Oct-02 22:30
Stuart Carter27-Oct-02 22:30 
QuestionHow do I drag files from one list control to another Pin
Bhikshapathi Gorantla24-Jul-02 19:07
Bhikshapathi Gorantla24-Jul-02 19:07 
AnswerRe: How do I drag files from one list control to another Pin
Stuart Carter24-Jul-02 23:58
Stuart Carter24-Jul-02 23:58 

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.