如何用鼠标移动图片? C#表格

时间:2013-01-25 10:41:25

标签: c# forms events mouse

我想用鼠标移动一个pictureBox,所以我到了这里:

    private void pictureB_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(image, recLoc);
    }
    private void pictureB_MouseDown(object sender, MouseEventArgs e)
    {
        WorkAble = true;
        choosingPoint.X = e.X;
        choosingPoint.Y = e.Y; 
        lastPoint.X = e.X;
        lastPoint.Y = e.Y;
    }

    private void pictureB_MouseMove(object sender, MouseEventArgs e)
    {
        if (WorkAble)
        {
            recLoc.X = e.X - choosingPoint.X;// + lastPoint.X;
            recLoc.Y = e.Y - choosingPoint.Y;// + lastPoint.Y;
            pictureB.Refresh();
        }
    }

    private void pictureB_MouseUp(object sender, MouseEventArgs e)
    {
        WorkAble = false;
        lastPoint.X = e.X;
        lastPoint.Y = e.Y;
    }
    // recLoc = pictureBox Location.
好吧,它很棒......但不完美...... 我的意思是一旦KeyUp事件被执行,你再次点击图像将返回到pictureBox的0,0点。 为了克服这个问题,我添加了lastPoint点,并在鼠标移动中添加了它的值。 因此,一方面它确实在最后一个丢弃点绘制图像,但是鼠标将位于图像的0,0点,而不是在我单击的位置 - 在图像上。就像我点击图像的中心一样,鼠标将位于0,0点......

任何建议如何解决?

2 个答案:

答案 0 :(得分:1)

对“recLoc”进行增量更改,以避免丢失原始位置:

private void pictureB_MouseMove(object sender, MouseEventArgs e)
{
    if (WorkAble)
    {
        recLoc.X = recLoc.X + e.X - choosingPoint.X;
        recLoc.Y = recLoc.Y + e.Y - choosingPoint.Y;
        choosingPoint = e.Location;
        pictureB.Invalidate();
    }
}

答案 1 :(得分:0)

private void pictureB_MouseDown(object sender, MouseEventArgs e)
    {
        WorkAble = true;
        lastPoint.X = e.X;
        lastPoint.Y = e.Y;
    }

        private void pictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            mouseMove = false;
            lastPointX = e.X;
            lastPointY = e.Y;
        }


private void pictureB_MouseMove(object sender, MouseEventArgs e)
{
    if (WorkAble)
    {
        recLoc.X -= (lastPoint.X - e.X);
        recLoc.Y -= (lastPoint.X - e.X);
        pictureB.Refresh();
        choosingPoint = e.Location;
    }
}