WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
There are already several articles on CodeGuru that 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 a 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 the checked state of dragged items.
- All code is encapsulated in the control—no changes are 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!