2015-04-02 125 views
1

我想捕获用户在datagridview中结束水平滚动的时刻。我需要这个来重新定位网格标题中的按钮。datagridview使用键盘滚动时滚动事件不会触发

我迄今所做的是增加一个scrollListener我这个链接上找到:How can I receive the "scroll box" type scroll events from a DataGridView?

这个作品非常好,exept使用的键盘,滚动不火的滚动事件。当我在滚动事件中将鼠标放在代码中时,它会声明“在鼠标或键盘操作移动滚动框时发生”。所以事件应该在用键盘滚动时触发,但事实并非如此。

我的代码是这样的:

bool addScrollListener(DataGridView dgv) 
    { 
     // capture horizonal scrolling and redirect to s_Scroll. Purpose is to redraw buttons after scrolling 
     bool Result = false; 

     Type t = dgv.GetType(); 
     PropertyInfo pi = t.GetProperty("HorizontalScrollBar", BindingFlags.Instance | BindingFlags.NonPublic); 
     ScrollBar s = null; 

     if (pi != null) 
      s = pi.GetValue(dgv, null) as ScrollBar; 

     if (s != null) 
     { 
      s.Scroll += new ScrollEventHandler(s_Scroll); 

      Result = true; 
     } 

     return Result; 
    } 

    void s_Scroll(object sender, ScrollEventArgs e) 
    { 
     // if grid is done scrolling horizontal, than redraw our buttons 
     if (e.Type == ScrollEventType.EndScroll) 
     { 
      // code works well, but only get here when scrolling with mouse 
      PositionButtons(); 
     } 
    } 

所以我的问题是,当使用鼠标s_Scroll事件被激发用户滚动,但使用s_Scroll事件不会触发在所有的键盘滚动时。

我的问题是我该如何解决这个问题,以便在两种情况下触发事件, ,如果不可行,还有另一种方法可以从datagridview捕获水平滚动的结尾。

+0

您是否尝试使用'ValueChanged'事件而不是'Scroll'事件? – Bioukh 2015-04-02 10:20:41

+0

您是否需要仅在用户完成滚动时发生按钮定位? – 2015-04-02 10:20:44

+0

ValueChanged事件听起来不错,但我怎么用它来发现用户已经停止了水平滚动?当用户按住右箭头键并且在滚动后例如8列时,比我想要做我的代码,而不是8次。 – GuidoG 2015-04-02 10:52:46

回答

1

DataGridView中,键盘动作由DataGridView处理以更新当前单元位置。

必须使用ScrollBar.ValueChanged事件,并比较ScrollBar.ValueScrollBar.Maximum做你想做什么。


你有另一种解决办法,做你想做的,而不是对ScrollBar.Scroll添加事件监听什么:处理DataGridView.Scroll事件,并验证在DataGridView通过使用DataGridView.FirstDisplayedScrollingRowIndex财产和DataGridView.DisplayedRowCount(true)方法向下滚动。

这会更简单和更安全。

+0

ValueChanged事件听起来不错,但我怎么用它来发现用户已经停止了水平滚动?当用户按住右箭头键并且在滚动后例如8列时,比我想要做我的代码,而不是8次。 – GuidoG 2015-04-02 10:52:13

+0

您使用滚动事件和FirstDisplayedScrollingRowIndex给出的示例,这不适用于垂直滚动而不是水平滚动吗?我需要水平滚动。 – GuidoG 2015-04-02 10:54:52

+0

它也适用于水平滚动这些方法:'FirstDisplayedScrollingColumnIndex'和'DisplayedColumnCount(true)'。 – Bioukh 2015-04-02 10:58:55