繁体   English   中英

C#-拖放和保持控件:扩展

[英]C# - Drag and Drop & Keep Control: Extension

很抱歉再次打扰类似的问题。 但是,我在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;

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

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

 PictureBox pb = (PictureBox)sender;
 pb.Left = e.X + pb.Left - MouseDownLocation.X;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM