Drag a Picture from the FlowOutPanel to the Picturebox

Here I suppose the purpose is to drag the image in pictureBox1 in the flowLayoutPanel to pictureBox2 in the form.

First, you can add a PictureBox named pictureBox1 into the flowLayoutPanel and add another PictureBox named pictureBox2 to the form, and write a picture into the pictureBox1, then you can to obtain the picture,The last step is to clear the picture in the pictureBox1. Just use the code as follow:

private void flowLayoutPanel1_MouseDown(object sender, MouseEventArgs e)
{
    pictureBox1.Select();
    pictureBox1.DoDragDrop(pictureBox1.Image, DragDropEffects.Copy);
}

private void pictureBox2_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.Bitmap))
    {
        e.Effect = DragDropEffects.Copy;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
    PictureBox pb = (PictureBox)sender;
    pb.Image = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
    pictureBox2.Image = pb.Image;
    pictureBox1.Image = null;
}

private void Form1_Load(object sender, EventArgs e)
{
    flowLayoutPanel1.AllowDrop = true;
    pictureBox2.AllowDrop = true;
    pictureBox1.Image = Image.FromFile(@"D:a.jpg");
}

In addition to this, I also use the way by judging MousePosition to achieve it, but occasionally the program will fail. I have not found a specific reason until now.The specific code is as follows:

private void Form1_Load(object sender, EventArgs e)
{
    flowLayoutPanel1.AllowDrop = true;
    pictureBox1.Image = Image.FromFile(@"D:a.jpg");
    pictureBox2.Image = null;
}

Image i = null;

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        i = pictureBox1.Image;
    }
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        if (pictureBox2.Bounds.Contains(MousePosition))
        {
            pictureBox2.Image = i;
            pictureBox1.Image = null;
        }
        else
        {
            i = null;
        }
    }
}

private void button1_Click_1(object sender, EventArgs e)
{
    pictureBox1.Image = null;
    pictureBox1.Image = Image.FromFile(@"D:a.jpg");
    pictureBox2.Image = null;
}
原文地址:https://www.cnblogs.com/jizhiqiliao/p/9897138.html