ListBox - usando o drag e drop entre 2 listbox
|Top Previous Next|
The other day, I received an email from a reader concerning Drag and Drop. Basically, he knew how to implement drag and
drop between components of the same form, but wanted to know how to implement it between different forms of the same
Basically, there is no difference. It all depends on how you treat the Source parameter of the Drag and Drop method handlers.
The Source parameter is referring to where the drag operation originated. It doesn't matter if it is another control on the same
form, or a control on another form. If you need to determine a general class of drag sources (such as "any listbox") you can
simply use the "is" and as" instructions to test and cast the Source parameter to that particular class. If you need to identify a
particular instance of a listbox, you will need to make sure that the unit that holds that instance has been added to the Uses
clause of the unit that is receiving the events.
All you need to do to test this capability is to start a new application with a form. Add a second form, and add a listbox to both
forms. Set both listboxes DragMode property to dmAutomatic and populate the lists with some text items. Now add the
following events to the listbox on each form:
procedure TForm1.ListBoxDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
Accept := (Source is TListBox);
procedure TForm1.ListBoxDragDrop(Sender, Source: TObject; X, Y: Integer); begin
if (Sender is TListBox) and (Source is TListBox) then
with Source as TListBox do
if ItemIndex >= 0 then
(Sender as TListBox).Items.Add(Items[ItemIndex]);
In this example, whenever we drag an object over a control, it tests to see if that control is a listbox. If it is, it shows the
appropriate cursor indicating that it will accept the dragged item. When we actually drop the object, it tests to make sure that
both the source and sender are both listboxes (Source is the one we are dragging from and Sender is the one we are dragging
to... remember Sender means the one that sent the event, not necessarily the one that sent the drag object). Once we determine
that, we simply add the item to one listbox and remove it from the other.
Of course you could do much more sophisticated testing of who is the drag source and drag target, but this should at least
highlight the basic structure...