Title: Drag and drop images in C#
This example shows how to drag and drop images in C#. The example Drag and drop text in C# explains basic drag and drop operations. See that example for the fundamentals.
One of the first things you must do before implementing drag and drop is set the AllowDrop property to true for the control that should accept a drop. For some reason, Visual Studio does not display this property in the properties window for the PictureBox control. IntelliSense doesn't even admit the property exists! Clearly Microsoft doesn't expect you to drag and drop images.
However, the Control class implements AllowDrop and PictureBox inherits from Control, so the property does exist. You simply need to set it in code at run time and you need to ignore IntelliSense's refusal to believe it exists. Microsoft says:
The PictureBox control is not designed to allow drag and drop procedures. However, since PictureBox inherits from control, it also inherits the AllowDrop property. To clarify this, in the next release of the documentation, the PictureBox.AllowDrop topic will be marked with the "for internal use only" boilerplate. Also, the PictureBox.AllowDrop property will not appear in intellisense if you are using the Visual Studio text editor.
Basically Microsoft says this is by design and most people wouldn't want to do this anyway. I have no clue what they are thinking.
Anyway the following code shows how the program sets this property at run time.
// Set the drop target PictureBox's AllowDrop property at run time.
// It is unavailable in the Properties window and doesn't
// even show up in IntelliSense!
private void Form1_Load(object sender, EventArgs e)
{
picDropTarget.AllowDrop = true;
}
The following code shows the other drag and drop event handlers used by this example.
// Start the drag.
private void picDragSource_MouseDown(object sender,
MouseEventArgs e)
{
// Start the drag if it's the right mouse button.
if (e.Button == MouseButtons.Right)
{
picDragSource.DoDragDrop(picDragSource.Image,
DragDropEffects.Copy);
}
}
// Allow a copy of an image.
private void picDropTarget_DragEnter(object sender,
DragEventArgs e)
{
// See if this is a copy and the data includes an image.
if (e.Data.GetDataPresent(DataFormats.Bitmap) &&
(e.AllowedEffect & DragDropEffects.Copy) != 0)
{
// Allow this.
e.Effect = DragDropEffects.Copy;
}
else
{
// Don't allow any other drop.
e.Effect = DragDropEffects.None;
}
}
// Accept the drop.
private void picDropTarget_DragDrop(object sender,
DragEventArgs e)
{
picDropTarget.Image =
(Bitmap)e.Data.GetData(DataFormats.Bitmap, true);
}
Download the example to experiment with it and to see additional details.
|