382
LESSON 33 Providing drag and droP
In DragSource, allow Copy and Move operations. Check the result of
DoDragDrop and if the
operation was a Move, remove the text from the source
Label control.
1. Pass the DoDragDrop function the parameter DragDropEffects.Copy |
DragDropEffects.Move
for the allowed operations.
2. Check the result returned by DoDragDrop. If the result is DragDropEffects.Move,
clear the
Label control.
3. The code should look something like this:
// 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 copy and move.
if (dragLabel.DoDragDrop(data,
DragDropEffects.Copy | DragDropEffects.Move)
== DragDropEffects.Move)
{
// This is a Move. Remove the data from this application.
dragLabel.Text = “”;
}
}
In DropTarget, make the
DragEnter event handler allow Copy and Move operations.
1. In the DragEnter event handler, if text data is available set e.Effect =
DragDropEffects.Copy | DragDropEffects.Move
to allow both Copy and Move
operations. The code should look something like this:
// A drag entered. List available formats.
private void Form1_DragEnter(object sender, DragEventArgs e)
{
// Allow text data.
if (e.Data.GetDataPresent(DataFormats.Text))
{
// Only allow the Copy and Move operations.
e.Effect = DragDropEffects.Copy | DragDropEffects.Move;
}
}
In DropTarget, add a
DragOver event handler. The value e.KeyState & 8 is nonzero if the
Ctrl key is pressed. If Ctrl is pressed, allow Copy. If Ctrl is not pressed, allow Move.
1. Add the DragOver event handler. If Ctrl is pressed, set e.Effect =
DragDropEffects.Copy
. If Ctrl is not pressed, set e.Effect = DragDropEffects.Move.
// Allow copy or move depending on the Ctrl key state.
private void Form1_DragOver(object sender, DragEventArgs e)
596906c33.indd 382 4/7/10 12:34:40 PM