如何为ListView制作滚动事件

时间:2012-03-28 14:19:24

标签: c# winforms listview

我想在ListView中为滚动创建一个事件。

我找到了可行的方法,但它只在使用滚动条时触发事件。它不响应鼠标滚轮或箭头的滚动。

private const int WM_HSCROLL = 0x114;
private const int WM_VSCROLL = 0x115;

public event EventHandler Scroll;

protected void OnScroll()
{
   if (this.Scroll != null)
      this.Scroll(this, EventArgs.Empty);
}

protected override void WndProc(ref System.Windows.Forms.Message m)
{
   base.WndProc(ref m);
   if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL )
      this.OnScroll();
}

触发鼠标滚轮和键盘上/下按钮的滚动事件需要什么常量?

2 个答案:

答案 0 :(得分:5)

鼠标滚轮m.Msg值应为:

private const int WM_MOUSEWHEEL = 0x020A;

答案 1 :(得分:1)

我找到了其他常量,用于在向下箭头键和键盘上的结束键上进行滚动。这是CustomListView的代码

using System;
using System.Windows.Forms;

class MyListView : ListView
{
    public event ScrollEventHandler Scroll;
    private const int WM_HSCROLL = 0x114;
    private const int WM_VSCROLL = 0x115;
    private const int MOUSEWHEEL = 0x020A;
    private const int KEYDOWN = 0x0100;

    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 == MOUSEWHEEL || m.Msg == WM_VSCROLL || (m.Msg == KEYDOWN && (m.WParam == (IntPtr)40 || m.WParam == (IntPtr)35)))
        {
            // Trap WM_VSCROLL 
            OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), 0));
        }
    }
}