There are already several articles on CodeGuru which describe aspects of drag and drop in list and tree controls, particularly Dragging Items to Rearrange Rows by Wayne Berthin, and CreateDragImage for multiple selected items in CListCtrl by Frank Kobs. Unfortunately, none of these articles present a complete solution with working code, which is thus the purpose of this contribution.
This article includes a demo project, a CListCtrl derived class, and a release build exe for quick demonstration of the capabilities of the class. I don't intend the class to be all singing and dancing, but it is good enough for me to use in my current project. No doubt there are further enhancements that could be made it, so please be my guest.
The new class, CDragDropListCtrl, has the following features:
- Supports dragging of single and multiple selections.
- Potential drag targets are highlighted (selected) as the mouse moves over them.
- The list control will scroll when you try to drag out of the top or bottom.
- Horizontal mouse movement is ignored; if the mouse is to the left or right of the list control, dragging still occurs as though the mouse is over the control.
- Works with LVS_EX_FULLROWSELECT style on or off.
- Preserves checked state of dragged items.
- All code encapulated in the control - no changes required to the parent class.
The class grew out of the original article by Wayne Berthin, but I've rewritten most of the code, and added a heap more. The CreateDragImageEx method is almost the same as that given by Frank Kobs, with a minor bug fix so that it works correctly when the LVS_EX_FULLROWSELECT style is not set.
To use the new class, first add the DragDropListCtrl.cpp and DragDropListCtrl.h files to your project. Then add a list control to your dialog resource, and set the View style to Report. Use ClassWizard to add a variable for the list control. The Category for the variable should be Control, and the Variable type should be CDragDropListCtrl. Finally add this line to the top of your dialog header file:
That's all there is to it!
DownloadsDownload demo project - 16 Kb
Download exe - 8 Kb
Download source - 6 Kb