Mega Code Archive
Moving items in a TListBox using the mouse
Title: Moving items in a TListBox using the mouse
Question: This little example shows you how to move items in a listbox using the mouse. You could compare this too the way one moves songs in a winamp playlist.
Answer:
NOTE: This is just a small example that shows you this effect.
The following steps have to be followed in order to obtain a working example:
1. Set the dragmode property of the TListBox to dmAutomatic.
Next, you'll have to provide two event handler for the DragDrop and the
DragOver event of the TListBox.
2. Put the following code in the DragOver event handler.
procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
var
DropIndex: Integer;
TempStr : String;
begin
with TListBox(Sender) do
begin
DropIndex := ItemAtPos(Point(X,Y), True);
if (DropIndex -1) and (DropIndex ItemIndex) then
begin
TempStr := Items[DropIndex];
Items[DropIndex] := Items[ItemIndex];
Items[ItemIndex] := TempStr;
ItemIndex := DropIndex;
end;
end;
end;
3. And finally put this little of code in the DragDrop event handler.
procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X,
Y: Integer);
var
DropIndex: Integer;
begin
DropIndex := TListBox(Sender).ItemAtPos(Point(X,Y),False);
with TListBox(Source) do
begin
TListBox(Sender).Items.Insert(DropIndex, Items[ItemIndex]);
Items.Delete(ItemIndex);
end;
end;
Voila, there you go. You should be able now to move items in a listbox
using the mouse. This code also shows the item moving along through the
other items while you drag it. The code can be easily adjusted to prevent
this from happening. It's all pretty straight forward so I didn't bother
to comment the code.
Regards,
Chris
Tested with Delphi 6 Professional on WinXP Professional)