Adding Drag & Drop to a TListBox

How do I do drag and drop in a TListbox?


Adding Drag and Drop facilities to a listbox is a matter of checking to see if there is an item under the mouse pointer in the MouseDown event, and if so save the item text and the index number to variables.  Then check the MouseUp event to see if there is a different item under the mouse.  If so, delete the old item and insert a copy of it in the new position.

Firstly, add three variables to the private section:

  { Private declarations }
  Dragging: Boolean;
  OldIndex: Integer;
  TempStr: String;

Then add the following code to the MouseUp and MouseDown events:

procedure TForm1.ListBox1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var 
  Index: integer;
begin
  if Dragging then
    begin
      Index := ListBox1.ItemAtPos(point(x, y), true);
      if (Index > -1) and (Index <> OldIndex) then
        begin
          ListBox1.Items.Delete(OldIndex);
          ListBox1.Items.Insert(Index, TempStr);
          ListBox1.ItemIndex := Index; 
        end;
    end; 
  Dragging := false;
end;

procedure TForm1.ListBox1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var 
  Index: integer;
begin
  Index := ListBox1.ItemAtPos(point(x, y), true);
  if Index > -1 then
    begin
      TempStr := ListBox1.Items[Index];
      OldIndex := Index;
      Dragging := true;
    end; 
end;

Chris Bray.