本文介绍了一个简单的平移PictureBox(Winforms)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C#winforms中实现平移pictureBox.我有一个将autoScroll属性设置为true的面板.在面板中,我有我的pictureBox,其sizeMode设置为autoSize.在pictureBox上,我正在听鼠标事件,如:

I want to implement a panning pictureBox in C# winforms. I have a panel on which the autoScroll property is set to true. Within the panel I have my pictureBox whose sizeMode is set to autoSize. On the pictureBox I am listening to mouse events like so:

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),则在松开按钮后,图像将被平移几秒钟,并且输出为:

The problem is that after I release the button something still keeps firing mouseMove events and the image is very slowly being panned by much more then it should be. If I drag the image by a few pixels (maybe 2 or 3) then after releasing the button the image is being panned for a few a seconds and the output is:

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

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

a.s.o ....

a.s.o....

推荐答案

很难猜测.但是,您的鼠标坐标处理不正确,它将使PB快速发送到遥远的角落.而且不要调用表单的Refresh()方法,重新绘制它毫无意义.修复:

Hard to guess. Your mouse coordinate handling is however wrong, it will send the PB quickly into far away corner. And don't call the form's Refresh() method, there's no point in repainting it. Fix:

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

这篇关于一个简单的平移PictureBox(Winforms)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 12:59