How to Drag and drop image from one PictureBox to another PictureBox in C#
By FoxLearn 7/19/2024 2:16:47 AM 10.45K
How to Drag and drop image from one PictureBox to another PictureBox in C#
Create a new Windows Forms Application in Visual Studio, then place two PictureBox controls on the form. You can do this in the designer or in code, then design a simple UI to help you drag and drop image to the PictureBox in c# as shown below.
Adding a Form_Load event handler to your form that allows you to initialize the PictureBox controls.
private void Form1_Load(object sender, EventArgs e) { pictureBox1.AllowDrop = true; pictureBox2.AllowDrop = true; }
Set the AllowDrop
property of both PictureBox controls to true
.
Next, Add the DragDrop event handler to the PictureBox1 allows you to drag drop an image file to the PictureBox control as the following c# code.
private void pictureBox1_DragDrop(object sender, DragEventArgs e) { var data = e.Data.GetData(DataFormats.FileDrop); if (data != null) { var fileNames = data as string[]; if (fileNames.Length > 0) pictureBox1.Image = Image.FromFile(fileNames[0]); } }
And don't forget to add the DragEnter event handler to the PictureBox1 allows you to copy an image.
private void pictureBox1_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; }
Implement event handlers for the drag events (MouseDown
, DragEnter
, and DragDrop
) of the PictureBox from which you want to drag the image.
Adding the MouseDown event handler to the PictureBox1 to perform image copying.
private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) pictureBox1.DoDragDrop(pictureBox1.Image, DragDropEffects.Copy); }
Adding the DragEnter to the PictureBox2 allows you to copy an image.
private void pictureBox2_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.Bitmap) && (e.AllowedEffect & DragDropEffects.Copy) != 0) e.Effect = DragDropEffects.Copy; else e.Effect = DragDropEffects.None; }
Finally, Add the DragDrop event handler to the PictureBox2 to allows you to copy an image from clipboard as the following c# code.
private void pictureBox2_DragDrop(object sender, DragEventArgs e) { pictureBox2.Image = (Bitmap)e.Data.GetData(DataFormats.Bitmap, true); }
Press F5 to run your project, then drag and drop image to PictureBox1. Next, you can drag and drop the image from PictureBox1 to PictureBox2.
In this example, when you click and drag on pictureBox1
, the MouseDown
event handler copy the original location of the image.
The second PictureBox (pictureBox2
) is set up to accept the drop. In the DragEnter
event, it checks if the dropped data is of type Bitmap, and if so, it allows the drop operation. In the DragDrop
event, it retrieves the dropped image and sets it as its own image.
VIDEO TUTORIAL