如何拖动动态创建的图片框? [英] How can I drag dynamically created pictureboxes?

查看:98
本文介绍了如何拖动动态创建的图片框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我在for循环内部创建了这段代码。

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

因此,我知道在 picMouseMove中, i具有for循环结束时的值。

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

我要做的是在 picMouseMove事件上获取pic [i] id,以便用户实际上可以成功地拖动拼图。

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.

推荐答案

您需要投射 发件人 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();
    }
}

这篇关于如何拖动动态创建的图片框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆