Windows Forms: Drag and drop image from one PictureBox to another PictureBox in C#
By FoxLearn 1/24/2021 1:34:24 AM 10.11K
To create a simple application on how to use c# drag and drop image to picturebox, you can drag a PictureBox control from the Visual Studio toolbox into your form designer, 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; }
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; }
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.
VIDEO TUTORIAL