Starting a Drag Operation

From RAD Studio
Jump to: navigation, search

Go Up to Implementing Drag and Drop in Controls

Every control has a property called DragMode that determines how drag operations are initiated. If DragMode is dmAutomatic, dragging begins automatically when the user presses a mouse button with the cursor on the control. Because dmAutomatic can interfere with normal mouse activity, you may want to set DragMode to dmManual (the default) and start the dragging by handling mouse-down events.

To start dragging a control manually, call the control's BeginDrag method. BeginDrag takes a Boolean parameter called Immediate and, optionally, an integer parameter called Threshold. If you pass True for Immediate, dragging begins immediately. If you pass False, dragging does not begin until the user moves the mouse the number of pixels specified by Threshold.


 BeginDrag (False,-1);
BeginDrag (false, -1);

allows the control to accept mouse clicks without beginning a drag operation.

You can place other conditions on whether to begin dragging, such as checking which mouse button the user pressed, by testing the parameters of the mouse-down event before calling BeginDrag. The following code, for example, handles a mouse-down event in a file list box by initiating a drag operation only if the left mouse button was pressed.

 procedure TFMForm.FileListBox1MouseDown(Sender: TObject;
   Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
   if Button = mbLeft then  { drag only if left button pressed }
     with Sender as TFileListBox do  { treat Sender as TFileListBox }
         if ItemAtPos(Point(X, Y), True) >= 0 then  { is there an item here? }
           BeginDrag(False);  { if so, drag it }
void __fastcall TFMForm::FileListBox1MouseDown(TObject *Sender,
		TMouseButton Button, TShiftState Shift, int X, int Y) {
	if (Button == mbLeft) // drag only if left button pressed
		TFileListBox *pLB = (TFileListBox*)Sender; // cast to TFileListBox
		if (pLB->ItemAtPos(Point(X, Y), true) >= 0) // is there an item here?
					pLB->BeginDrag(false, -1); // if so, drag it

See Also