在c#中处理listview上的滚动事件

mur*_*ki5 16 c# listview scroll event-handling

我有一个listview,使用backgroundworker生成缩略图.当滚动列表视图时,我想暂停背景工作并获得滚动区域的当前值,当用户停止滚动列表视图时,根据滚动区域的值从项目开始恢复背景工作.

是否可以处理列表视图的滚动事件?如果有,怎么样?如果不是那么根据我上面描述的那个什么是一个好的选择?

Han*_*ant 21

您必须添加对ListView类的支持,以便您可以收到有关滚动事件的通知.在项目中添加一个新类并粘贴下面的代码.编译.将新的listview控件从工具箱顶部拖放到表单上.为新的Scroll事件实现处理程序.

using System;
using System.Windows.Forms;

    class MyListView : ListView {
      public event ScrollEventHandler Scroll;
      protected virtual void OnScroll(ScrollEventArgs e) {
        ScrollEventHandler handler = this.Scroll;
        if (handler != null) handler(this, e);
      }
      protected override void WndProc(ref Message m) {
        base.WndProc(ref m);
        if (m.Msg == 0x115) { // Trap WM_VSCROLL
          OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), 0));
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)

请注意滚动位置(ScrollEventArgs.NewValue)没有意义,它取决于ListView中的项目数.我强制它为0.根据您的要求,您希望查看ScrollEventType.EndScroll通知以了解用户何时停止滚动.其他任何东西都可以帮助您检测用户是否开始滚动.例如:

ScrollEventType mLastScroll = ScrollEventType.EndScroll;

private void myListView1_Scroll(object sender, ScrollEventArgs e) {
  if (e.Type == ScrollEventType.EndScroll) scrollEnded();
  else if (mLastScroll == ScrollEventType.EndScroll) scrollStarted();
  mLastScroll = e.Type;
}
Run Code Online (Sandbox Code Playgroud)

  • 阅读http://stackoverflow.com/questions/1176703/listview-onscroll-event/1182232#1182232以查看WM_VSCROLL消息的一些限制. (3认同)