0

我想在 C# winforms 中实现一个平移图片框。我有一个将 autoScroll 属性设置为 true 的面板。在面板中,我有我的图片框,其 sizeMode 设置为 autoSize。在图片框上,我正在监听鼠标事件,如下所示:

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        dragging = true;
        start = new Point(e.Location.X + pictureBox1.Location.X, e.Location.Y + pictureBox1.Location.Y);
    }
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (dragging)
    {
        Debug.WriteLine("mousemove X: " + e.X + " Y: " + e.Y);

        pictureBox1.Location = new Point(start.X - e.Location.X, start.Y - e.Location.Y);
        this.Refresh();
    }
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    Debug.WriteLine("mouseup");

    dragging = false;
}

问题是,在我释放按钮后,某些东西仍然会触发 mouseMove 事件,并且图像的平移速度非常缓慢,远远超过了它应该的水平。如果我将图像拖动几个像素(可能是 2 或 3),那么在释放按钮后,图像将被平移几秒钟,输出为:

mousemove X: 66 Y: 37 mousemove X: 66 Y: 38 mousemove X: 66 Y: 39 mousemove X: 66 Y: 40 mousemove X: 66 Y: 41 mousemove X: 66 Y: 42 mousemove X: 66 Y: 43 mousemove X: 66 Y: 44 mousemove X: 66 Y: 45 mousemove X: 66 Y: 46

阿苏...

4

1 回答 1

4

很难猜。然而,您的鼠标坐标处理是错误的,它会将 PB 快速发送到远处的角落。并且不要调用表单的 Refresh() 方法,重新绘制它是没有意义的。使固定:

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
        if (e.Button == MouseButtons.Left) {
            dragging = true;
            start = e.Location;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
        if (dragging) {
            Debug.WriteLine("mousemove X: " + e.X + " Y: " + e.Y);

            pictureBox1.Location = new Point(pictureBox1.Left + e.Location.X - start.X,
                pictureBox1.Top + e.Location.Y - start.Y);
        }
    }
于 2012-01-24T11:19:25.237 回答