How can I drag dynamically created pictureboxes?

故事扮演 提交于 2019-12-24 18:03:05

问题


So, I have a form with a background image (picturebox) and some jigsaw puzzle pieces (pictureboxes created dynamically named pic[i]) on random locations.

I have this piece of code inside the for-loop creating the pieces.

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

And below I show the corresponding events.

    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;
    }

So, I am aware that inside the "picMouseMove", "i" has the value it had when the for loop ended.

What I want to do is to get the pic[i] id on the "picMouseMove" event so the user can actually drag the puzzle piece successfully.


回答1:


You need to cast the sender to a PictureBox. Then you can access it as if you knew it by name.

Simply change

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

to

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


来源:https://stackoverflow.com/questions/24475152/how-can-i-drag-dynamically-created-pictureboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!