c# - 在鼠标移动时设置自动滚动位置

标签 c# winforms

当我点击图像并移动图片框时,我需要更新滚动条位置。它总是在起点,它只在右侧(水平)和向下(垂直)移动。

    private void pictureBox1_MouseMove_1(object sender, MouseEventArgs e)
    {

            ....

            Point currentMousePos = e.Location;
            int distanceX = currentMousePos.X - mouseX;
            int distanceY = currentMousePos.Y - mouseY;
            int newX = pictureBox1.Location.X + distanceX;
            int newY = pictureBox1.Location.Y + distanceY;

            if (newX + pictureBox1.Image.Width + 10 < pictureBox1.Image.Width && pictureBox1.Image.Width + newX + 10 > panel1.Width)
            {
                pictureBox1.Location = new Point(newX, pictureBox1.Location.Y);
            }
            if (newY + pictureBox1.Image.Height + 10 < pictureBox1.Image.Height && pictureBox1.Image.Height + newY + 10 > panel1.Height)
            {
                pictureBox1.Location = new Point(pictureBox1.Location.X, newY);
            }
    }

最佳答案

我认为您需要更改父面板的 AutoScrollPosition 而不是摆弄 PictureBoxLocation 点。毕竟,父面板的滚动条已经负责了 PictureBox 的位置。

尝试这样的事情(顺便说一句,我的代码只在按下按钮时执行此操作,否则,我认为这将是一个奇怪的用户界面设计):

private Point _StartPoint;

void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left)
    _StartPoint = e.Location;
}

void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    Point changePoint = new Point(e.Location.X - _StartPoint.X, 
                                  e.Location.Y - _StartPoint.Y);
    panel1.AutoScrollPosition = new Point(-panel1.AutoScrollPosition.X - changePoint.X,
                                          -panel1.AutoScrollPosition.Y - changePoint.Y);
  }
}

关于c# - 在鼠标移动时设置自动滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8543802/

相关文章:

c# - => 和 get {} 之间的区别

c# - Windows 窗体的大小是否包括其边框?

c# - 让 Winform 同时出现在所有现有监视器上(它是一个警报窗口)

c# - 归并排序问题

c# - Update-Database 由于未决更改而失败,但 Add-Migration 创建了重复迁移

c# - 如果缺少字段,CsvHelper 将丢弃行

面向初学者的 C# GUI 编程 : Where to start?

vb.net - winforms VB中绘制进度条控件的反射

c# - 指南针 UI 和指针

c# - 在 c# 2.0 中阻止/重定向 IP 或没有主机文件的主机