Aug 18, 2009

Windows Forms : Use Drag-and-Drop

Windows Forms : Use Drag-and-Drop


This code will show you how to implement drag and drop functionality in a
Windows Form. Drag-and-drop is one of the fundamental metaphors underlying the
Microsoft Windows family of operating systems. Users understand that some
items can be moved around by holding the mouse down on them, and that they'll
get appropriate visual feedback when they're over a spot where the item can be
dropped. They expect to be able to move data and images from one spot to
another this way. You can control all aspects of the process, including which
controls allow dragging, what data they make available to drag, and where it
can be dropped. You can implement this both within a single application and
between applications.

Featured Highlights:

a) From a TextBox control to two other TextBox controls, one of which does not
have the AllowDrop property set to True, demonstrating how to prevent a drop on
a control.


The MouseDown event for the left TextBox. This event fires when the mouse is in the control's bounds and the mouse button is clicked.

Declare constant for use in detecting whether the Ctrl key was pressed during the drag operation.





const byte CtrlMask = 8;





private void TextBoxLeft_MouseDown(object sender,
System.Windows.Forms.MouseEventArgs e)

{

if (e.Button == MouseButtons.Left)

{

txtLeft.SelectAll();

//invoke the drag and drop operation

txtLeft.DoDragDrop(txtLeft.SelectedText, DragDropEffects.Move |
DragDropEffects.Copy);

}

}



// the DragDrop event for the lower right TextBox. This event fires

// when the mouse button is released, terminating the drag-and-drop
operation.



private void TextBoxLowerRight_DragDrop(object sender,
System.Windows.Forms.DragEventArgs e)

{

txtLowerRight.Text = e.Data.GetData(DataFormats.Text).ToString();

// if the Ctrl key was not pressed, remove the source text to effect a

// drag-and-drop move.



if ((e.KeyState & CtrlMask) != CtrlMask)

{

txtLeft.Text = "";

}

}



// the DragEnter event for the lower right TextBox. DragEnter is the

// event that fires when an object is dragged into the control's bounds.



private void TextBoxLowerRight_DragEnter(object sender,
System.Windows.Forms.DragEventArgs e)

{

// Check to be sure that the drag content is the correct type for this

// control. if not, reject the drop.



if (e.Data.GetDataPresent(DataFormats.Text))

{

// if the Ctrl key was pressed during the drag operation then perform a
Copy. if not, perform a Move.



if ((e.KeyState & CtrlMask) == CtrlMask)

{

e.Effect = DragDropEffects.Copy;

}

else

{

e.Effect = DragDropEffects.Move;

}

}

else

{

e.Effect = DragDropEffects.None;

}

}

2 comments:

  1. Hay,

    Its a basic one !


    AND NICE POST ANYTHING MORE ?

    .............................

    ReplyDelete