The DragSource example program (available in this lesson’s code download) uses the following code
to start dragging text when you press the right mouse button down over its
dragLabel control:
// Start a drag.
private void dragLabel_MouseDown(object sender, MouseEventArgs e)
{
// If it’s not the right mouse button, do nothing.
if (e.Button != MouseButtons.Right) return;
// Make the data object.
DataObject data = new DataObject(DataFormats.Text, dragLabel.Text);
// Start the drag allowing only copy.
dragLabel.DoDragDrop(data, DragDropEffects.Copy);
}
The code first checks whether the right mouse button is pressed and exits if it is not. It then creates
a
DataObject. It passes the object’s constructor the value DataFormats.Text to indicate that it will
hold text data and the text that the object should hold.
Finally, the code calls the
Label control’s DoDrag method passing it the DataObject and the value
DragDropEffects.Copy to indicate that the drag allows only the copy operation.
This example doesn’t bother with the
GiveFeedback and QueryContinueDrag event handlers, so
that’s the extent of its participation in the drag.
The DoDrag function returns a DragDropEffects value that indicates what the
drop target decided to do with the data. For example, if the function returns
DragDropEffects.Move, then the user is performing a Move operation so the
drag source should remove the data from its application. For example, a file
explorer such as Windows Explorer would remove the file from the source
location and move it to the drop location.
Note that a drag is completely separate from the drop target. If a drop target can accept the data,
it is free to do so. That means you don’t need to wait until you read about the DropTarget example
program described in the next section to test the DragSource program. You can test the program
right now by using it to drag text data into Word, WordPad, or any other program that accepts
dropped text. (Notepad doesn’t know how to accept dropped text.)
CATCHING A DROP
Before a control can accept a drop, you must set the form’s AllowDrop property to true. If
AllowDrop is false, the form will not allow drops no matter what event handlers you create.
The only other thing a drop target must do is provide
DragEnter and DragDrop event handlers.
596906c33.indd 379 4/7/10 12:34:39 PM