C#-拖放&;保持控制:扩展
本文关键字:控制 扩展 拖放 amp C#- | 更新日期: 2023-09-27 18:29:36
很抱歉再次遇到类似的问题。然而,我在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。但是,我需要制作它,这样我就可以生成尽可能多的图像,而无需将其放在页面顶部,这使得它一次只使用一个图像。
您制作的每个picturebox都被路由到这些事件,因此sender
对象就是picturebox,您只需要将其转换为正确的类型,然后移动它。
PictureBox pb = (PictureBox)sender;
pb.Left = e.X + pb.Left - MouseDownLocation.X;