获取用户是否正在滚动DataGridView

时间:2013-08-12 05:53:45

标签: c# winforms datagridview

我正在寻找用户当前是否按住垂直滚动条。

这个问题产生于更新DataGridView的DataSource时取消滚动的事实。

我希望将IsUserScrolling()这样的扩展方法放在DataGridView上。我的想法是,在用户停止滚动之前,我不会更新DataGridView。

2 个答案:

答案 0 :(得分:2)

您可以知道用户是否通过DataGridView事件滚动Scroll,您可以知道用户是否在Thumb上按住鼠标并通过其ScrollEventArgs滚动,如下所示:

private void dataGridView1_Scroll(object sender, ScrollEventArgs e){
  if(e.ScrollOrientation == ScrollOrientation.VerticalScroll &&
     (e.Type == ScrollEventType.LargeIncrement || e.Type == ScrollEventType.LargeDecrement)){
     //your code here
  }
}

上面的代码几乎运行良好,但不知何故,你可以用VerticalScroll.Value以编程方式更改Large Change(这不存在),即使用户没有按住鼠标,事件也会被触发在垂直拇指上。因此,我们可以添加条件MouseButtons == MouseButtons.Left以使其更好地运行:

private void dataGridView1_Scroll(object sender, ScrollEventArgs e){
  if(e.ScrollOrientation == ScrollOrientation.VerticalScroll && MouseButtons == MouseButtons.Left &&
     (e.Type == ScrollEventType.LargeIncrement || e.Type == ScrollEventType.LargeDecrement)){
     //your code here
  }
}

使用Thumb方法检测用户是否在垂直滚动条(Arrow Repeat buttonHitTest)上的任何位置按住鼠标的另一种简短方法,您可以添加更多代码以使其更有效可靠,这样我们就不会错过某种带有真实用户滚动动作的程序化滚动:

private void dataGridView1_Scroll(object sender, ScrollEventArgs e){
  Point p = dataGridView1.PointToClient(MousePosition);
  if (dataGridView1.HitTest(p.X, p.Y).Type == DataGridViewHitTestType.VerticalScrollBar){
     //Your code here
  }
}

答案 1 :(得分:0)

我搜索了它并找到了答案。它可能不是完美的答案,但它有效:

我创建了dataGridView,并创建了hScrollBar,将hScrollBar放在dataGridView滚动条的顶部(您可以使用vScrollBar如果你的意思是垂直),将滚动条的宽度设置为与dataGridView相同,在Scroll事件中,我做了:

  private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
  {
     dataGridView1.HorizontalScrollingOffset = hScrollBar1.Value;
  }

这样您就可以使用MouseDown的{​​{1}}和MouseUp个事件。你顺利来吧