如何在接近面板边框时自动向上或向下滚动

本文关键字:滚动 接近 边框 | 更新日期: 2023-09-27 18:35:07

就像在Word中一样,任何浏览器和大量其他应用程序一样,当将对象拖到面板的可见区域之外时,如何使面板的内容向上或向下滚动?

这是我最接近我正在寻找的东西,但它仍然不完美。

private void Werkorders_DragOver(object sender, DragEventArgs e)
{
    grpWerkorders.AutoScrollPosition = grpWerkorders.PointToClient(new Point(e.X, e.Y));
}

如何在接近面板边框时自动向上或向下滚动

这可以使用WinForms Timer来完成。 示例代码:

private Timer scrollTimer = new Timer();
private int scrollJump = 0;
public Form1() {
  InitializeComponent();
  panel1.AllowDrop = true;
  panel1.AutoScroll = false;
  panel1.AutoScrollMinSize = new Size(0, 1000);
  panel1.MouseMove += panel1_MouseMove;
  panel1.DragEnter += panel1_DragEnter;
  panel1.DragOver += panel1_DragOver;
  panel1.QueryContinueDrag += panel1_QueryContinueDrag;
  scrollTimer.Tick += scrollTimer_Tick;
}

拖动事件:

void panel1_MouseMove(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    panel1.DoDragDrop("test", DragDropEffects.Move);
  }
}
void panel1_DragEnter(object sender, DragEventArgs e) {
  e.Effect = DragDropEffects.Move;
}
void panel1_DragOver(object sender, DragEventArgs e) {
  Point p = panel1.PointToClient(new Point(e.X, e.Y));
  if (p.Y < 16) {
    scrollJump = -20;
    if (!scrollTimer.Enabled) {
      scrollTimer.Start();
    }
  } else if (p.Y > panel1.ClientSize.Height - 16) {
    scrollJump = 20;
    if (!scrollTimer.Enabled) {
      scrollTimer.Start();
    }
  } else {
    if (scrollTimer.Enabled) {
      scrollTimer.Stop();
    }
  }
}
void panel1_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) {
  if (e.Action != DragAction.Continue) {
    scrollTimer.Stop();
  }
}

定时器代码:

void scrollTimer_Tick(object sender, EventArgs e) {
  if (panel1.ClientRectangle.Contains(panel1.PointToClient(MousePosition))) {
    Point p = panel1.AutoScrollPosition;
    panel1.AutoScrollPosition = new Point(-p.X, -p.Y + scrollJump);
  } else {
    scrollTimer.Stop();
  }
}

您可以调整 scrollJump 值以增加或减少滚动条的更改量,或调整计时器的间隔量(默认为 100 毫秒)。