C# Drag and Drop from one Picture box into Another

user2250165 picture user2250165 · Apr 14, 2013 · Viewed 25.4k times · Source

I'm working in visual studio 2012 with C# and I need to Drag a Picture box into another picture box, basically replace the target Picturebox Image with the Dragged Picture box image.

How do I do this?

Please be specific and try to explain as simplest and as best as possible. I'm extremely new to programming, and a bit desperate so please be patient with me.

Answer

Hans Passant picture Hans Passant · Apr 15, 2013

Drag+drop is hidden on the PictureBox control. Not sure why, it works just fine. The probable guidance here is that it will not be obvious to the user that you could drop an image on the control. You'll have to do something about that, at least set the BackColor property to a non-default value so the user can see it.

Anyhoo, you'll need to implement the MouseDown event on the first picturebox so you can click it and start dragging:

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
        var img = pictureBox1.Image;
        if (img == null) return;
        if (DoDragDrop(img, DragDropEffects.Move) == DragDropEffects.Move) {
            pictureBox1.Image = null;
        }
    }

I assumed you wanted to move the image, tweak if necessary if copying was intended. Then you'll have to implement the DragEnter and DragDrop events on the second picturebox. Since the properties are hidden, you should set them in the form's constructor. Like this:

    public Form1() {
        InitializeComponent();
        pictureBox1.MouseDown += pictureBox1_MouseDown;
        pictureBox2.AllowDrop = true;
        pictureBox2.DragEnter += pictureBox2_DragEnter;
        pictureBox2.DragDrop += pictureBox2_DragDrop;
    }

    void pictureBox2_DragEnter(object sender, DragEventArgs e) {
        if (e.Data.GetDataPresent(DataFormats.Bitmap))
            e.Effect = DragDropEffects.Move;
    }

    void pictureBox2_DragDrop(object sender, DragEventArgs e) {
        var bmp = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
        pictureBox2.Image = bmp;
    }

This does allow you to drag an image from another application into the box. Let's call it a feature. Use a bool flag if you want to disallow this.