C#如何用鼠标移动图片框

时间:2014-11-22 20:53:21

标签: c#

我尝试在c#中做一个程序,你试图装饰一棵圣诞树,我想用鼠标选择地球仪并放在圣诞树上。我可以做到这一点,但只是为了一个图片框,我写了第二个图片框的代码,我运行程序,全球正在移动。 这是我的代码。怎么解决这个问题?
附: picturebox1和2是地球仪,pb_brad是圣诞树。

   public partial class Form1 : Form
{
    Point location = Point.Empty;
    public Form1()
    {
        InitializeComponent();
        pictureBox1.Parent = pb_brad;
        pictureBox1.BackColor = Color.Transparent;
        pictureBox2.Parent = pb_brad;
        pictureBox2.BackColor = Color.Transparent;

    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            location = new Point(e.X, e.Y);
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (location != Point.Empty)
        {
            Point newlocation = this.pictureBox1.Location;
            newlocation.X += e.X - location.X;
            newlocation.Y += e.Y - location.Y;
            this.pictureBox1.Location = newlocation;
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        location = Point.Empty;
    }

    private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            location = new Point(e.X, e.Y);
        }
    }

    private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
    {
        if (location != Point.Empty)
        {
            Point newlocation = this.pictureBox1.Location;
            newlocation.X += e.X - location.X;
            newlocation.Y += e.Y - location.Y;
            this.pictureBox2.Location = newlocation;
        }
    }

    private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
    {
        location = Point.Empty;
    }

}

1 个答案:

答案 0 :(得分:0)

我看到你在pictureBox2的MouseMove事件处理程序中使用了pictureBox1。

顺便说一下,我看到两个PictureBox的处理程序是相同的。为什么不对所有PictureBox使用相同的处理程序并通过sender参数获取当前的PictureBox?