我如何可以将动态创建pictureboxes?(How can I drag dynamically

2019-10-20 09:00发布

所以,我有一个背景图片(图片框)和一些七巧板上的任意位置(动态创建一个名为PIC [I] pictureboxes)的形式。

我有这样一段代码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”事件的知情同意[I] ID,以便用户可以真正成功拖动拼图。

Answer 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();
    }
}


文章来源: How can I drag dynamically created pictureboxes?