Check out this sample project at gotnetdot.com. It derives from Form and implements the owner drawing by handling the DrawItem event and MeasureItem event.
You can also download a sample that implements an owner drawn listbox by deriving from ListBox and overriding the virtual methods OnDrawItem and OnMeasureItem. Here is a OnDrawItem override that draws colored rectangles in the listbox.
protectedoverridevoidOnDrawItem(System.Windows.Forms.DrawItemEventArgs e){
//undo the selection rect on the old selectionif( oldSelectedRect != e.Bounds &&
oldSelectedIndex > -1 && oldSelectedIndex < Items.Count)
{
e.Graphics.DrawRectangle(new Pen((Color) Items[oldSelectedIndex], 2), oldSelectedRect);
}
//draw the item .. here we just fill a rectif( e.Index > -1 && e.Index < Items.Count)
e.Graphics.FillRectangle(new SolidBrush( (Color)Items[e.Index] ), e.Bounds);
//draw selection rect if neededif(SelectedIndex == e.Index)
{
e.Graphics.DrawRectangle(new Pen(Color.Black,2), e.Bounds);
oldSelectedRect = e.Bounds;
oldSelectedIndex = e.Index;
}
}
The code below minimally handles D&D for a single selection list box by handling four events. The D&D is initiated in MouseDown if the user mouses down on the current selection. The DragEnter event is used to set the dragging effect to copy if you are not over the drag source. The DragDrop event is used to do the drop. And finally, the SelectedIndexChanged event is used to track the current selection for use in the MouseDown event. You can download a working project (C#, VB). This project handles additional events to provide visual queues during the drop.
The samples referenced above do not allow dragging and dropping within the same listbox. Here is another set of samples that does allow you to drag and drop within the same listbox.
One more note. If your listboxes contain full file pathnames, you can support dropping these paths onto Windows Explorer by supporting the FileDrop dataformat. In the OnMouseDown override, if you replace the DoDragDrop line with the following code block, you will be able to drop files.
//put the file path is a string array
string[] files = new String[1];
files[0] = SelectedItem.ToString();
//create a dataobject holding this array as a filedrop
DataObject data = new DataObject(DataFormats.FileDrop, files);
//also add the selection as textdata
data.SetData(DataFormats.StringFormat, SelectedItem.ToString());
//do the dragdrop
DoDragDrop(data, DragDropEffects.Copy);