【问题标题】:How can I drag dynamically created pictureboxes?如何拖动动态创建的图片框?
【发布时间】:2014-08-19 22:34:43
【问题描述】:

所以,我有一个带有背景图像(图片框)和一些拼图块(动态创建的图片框,命名为 pic[i])的表单。

我在 for 循环中有这段代码来创建这些片段。

    pic[i].MouseDown += new MouseEventHandler(picMouseDown);
    pic[i].MouseMove += new MouseEventHandler(picMouseMove);
    pic[i].MouseUp += new MouseEventHandler(picMouseUp);

下面我展示了相应的事件。

    int x = 0;
    int y = 0;
    bool drag = false;

    private void picMouseDown(object sender, MouseEventArgs e)
    {
        // Get original position of cursor on mousedown
        x = e.X;
        y = e.Y;
        drag = true;
    }

    private void picMouseMove(object sender, MouseEventArgs e)
    {
        if (drag)
        {
            // Get new position of picture
            pic[i].Top += e.Y - y;    //this i here is wrong
            pic[i].Left += e.X - x;
            pic[i].BringToFront();
        }
    }

    private void picMouseUp(object sender, MouseEventArgs e)
    {
        drag = false;
    }

所以,我知道在“picMouseMove”内部,“i”具有 for 循环结束时的值。

我想做的是在“picMouseMove”事件中获取 pic[i] id,以便用户可以成功拖动拼图。

【问题讨论】:

    标签: c# controls picturebox drag


    【解决方案1】:

    您需要将sender转换PictureBox。然后您就可以像知道它的名字一样访问它。

    简单的改变

    private void picMouseMove(object sender, MouseEventArgs e)
    {
        if (drag)
        {
            // Get new position of picture
            pic[i].Top += e.Y - y;    //this i here is wrong
            pic[i].Left += e.X - x;
            pic[i].BringToFront();
        }
    }
    

    private void picMouseMove(object sender, MouseEventArgs e)
    {
        if (drag)
        {
            PictureBox pb = (PictureBox ) sender;
            // Get new position of picture
            pb.Top += e.Y - y;    
            pb.Left += e.X - x;
            pb.BringToFront();
        }
    }
    

    【讨论】:

    • 非常好,谢谢,虽然“pb.Y”是错误的。 "PictureBox pb = (PictureBox) 发件人;"解决它:)
    猜你喜欢
    • 2020-07-09
    • 2020-10-08
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多