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;
在flower2名下的所有单词。这是因为,我已经在pictureBox2_Click中定义了flower2,所以每次点击一个新的PictureBox都会生成。但是,我需要制作它,以便我可以生成任意数量的图像而不将其放在页面的顶部,这使得它一次只使用一个图像。
答案 0 :(得分:0)
您制作的每个图片框都会路由到这些事件,因此sender
对象就是图片框,您只需要将其转换为正确的类型然后移动它。
PictureBox pb = (PictureBox)sender;
pb.Left = e.X + pb.Left - MouseDownLocation.X;