一个简单的平移 PictureBox (Winforms)
我想在 C# winforms 中实现平移图片框。我有一个面板,其 autoScroll 属性设置为 true。在面板中,我的图片框的 sizeMode 设置为 autoSize。在 pictureBox 上,我正在监听鼠标事件,如下所示:
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 鼠标移动 X: 66 Y: 38 鼠标移动 X:66 Y:39 鼠标移动 X:66 Y:40 鼠标移动 X:66 Y:41 鼠标移动 X: 66 Y: 42 鼠标移动 X:66 Y:43 鼠标移动 X: 66 Y: 44 鼠标移动 X:66 Y:45 mousemove X: 66 Y: 46
a.so...
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;
}
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
a.s.o....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很难猜测。然而你的鼠标坐标处理是错误的,它会将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: