C#拖放选择图片框从表单移动

时间:2013-10-27 11:48:28

标签: c# drag-and-drop picturebox

所以我有一个项目,我需要拖放不同的图片框,并在拖动它们时将它们的现有副本复制到表单中。我的问题是,在表单上创建后,我无法移动所选的“图片框”。我想有一个选项,我可以移动任何拖动的图片框,而不是像拖动一个位置并保持在那个位置。

    private void pictureBox_MouseDown(object sender, MouseEventArgs e)
    {


        if (e.Button == MouseButtons.Left)
        {
            p = (PictureBox)sender;
            p.Tag = p.Location;
            downPoint = e.Location;
            p.Parent = this;
            p.BringToFront();

        }

    }
    private void pictureBox_MouseMove(object sender, MouseEventArgs e)
    {
        p = (PictureBox)sender;
        if (e.Button == MouseButtons.Left)
        {
            p.Left += e.X - downPoint.X ;
            p.Top += e.Y - downPoint.Y ;


        }
    }
     private void pictureBox_MouseUp(object sender, MouseEventArgs e)
    {
        p = (PictureBox)sender;

        PictureBox PB = new PictureBox();


        Control c = GetChildAtPoint(new Point(p.Left -1, p.Top));
        if (c == null) c = this;
        Point newLoc = c.PointToClient(p.Parent.PointToScreen(p.Location));
        PB.Parent = c;
        PB.Location = newLoc;


       ;

        p.Parent.Controls.Add(PB); // <-- add new PB to the form!
        p.Location = (Point)p.Tag;
        // put the original back where it started:

    }

1 个答案:

答案 0 :(得分:0)

将事件放入新的图片框

PB.MouseMove += new MouseEventHandler(pictureBox_MouseMove);
PB.MouseDown += new MouseEventHandler(picturebOX_MouseDown);
PB.MouseUp += new MouseEventHandler(picturebOX_MouseUp);