0

很抱歉再次打扰类似的问题。但是,我在 C# 中的代码再次出现问题。我想给你到目前为止我得到的代码:

    private void pictureBox2_Click(object sender, EventArgs e)
    {
        PictureBox flower2 = new PictureBox();
        flower2.Image = Properties.Resources.Flower3;
        flower2.Location = new Point(panel1.Location.X + 10, panel1.Location.Y + 10);
        flower2.Size = new System.Drawing.Size(pictureBox2.Size.Width, pictureBox2.Size.Height);
        flower2.Parent = panel1;
        this.Controls.Add(flower2);

        flower2.BringToFront();
        flower2.MouseMove += new MouseEventHandler(flower2_MouseMove);
        flower2.MouseDown += new MouseEventHandler(flower2_MouseDown);
    }

    private void flower2_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
        }
    }

    private void flower2_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            flower2.Left = e.X + flower2.Left - MouseDownLocation.X;
            flower2.Top = e.Y + flower2.Top - MouseDownLocation.Y;
        }
    }

我想要它做的是当单击图像时,创建一个新图像并能够拖放它。只有当我将代码放在页面顶部时,我才成功。这不是我想要的,因为我希望能够添加任意数量的图像。我尝试了很多不同的方法。错误在:

      flower2.Left = e.X + flower2.Left - MouseDownLocation.X;
      flower2.Top = e.Y + flower2.Top - MouseDownLocation.Y;

在所有花名下的单词。这是因为,我在pictureBox2_Click 中定义了flower2,所以每次点击它都会生成一个新的PictureBox。但是,我需要制作它,以便我可以生成任意数量的图像,而无需将其放在页面顶部,这使得它一次只使用一张图像。

4

1 回答 1

0

您制作的每个图片框都会路由到这些事件,因此sender对象就是图片框,您只需将其转换为正确的类型然后移动它。

 PictureBox pb = (PictureBox)sender;
 pb.Left = e.X + pb.Left - MouseDownLocation.X;
于 2013-08-29T17:54:10.023 回答