Back



Drag & Drop Examples



When dragging and dropping an object from one application to another application or another component/location on a Form, you have a Source and a Destination.

The Destination is where the dragged item will end up.
The Source control holds the dragged item, you can define in your program the drag item as a complete control, like an image or just a selected portion such as a line in a ListBox.

All controls have a property called DragMode that determines how drag operations are initiated.
If  DragMode is dmAutomatic, then dragging happens automatically when the program user presses a mouse button with the cursor on the control.

The Events in a Drag & Drop operation happen in this order:
 

If you want the drag operation to work only if the left mouse key is pressed you can do this:

if Button = mbLeft then // drag only if left the button is pressed
 Put your code here!


Dragging from a ComboBox to a ListBox!

First put a ComboBox on the Form of a new project.
Then add a ListBox.

Click on the ComboBox and with the Object Inspector change the DragMode property to dmAutomatic.
Then add some text to ComboBox1 list of items (strings), maybe just a list of peoples names or something like that.
To do this look for 'items' in the Object Inspector then double-click on the ellipsis.

Next write these two event handlers:

procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer);
begin
  with Source as TComboBox do
     ListBox1.Items.Add(ComboBox1.Text);
end;

procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
  if Source = ComboBox1 then
    Accept := True
else
    Accept := False;
end;

Run the program and then select a name from the ComboBox list and then drag it over to the ListBox.




Back
Hosted by www.Geocities.ws

1