自定义ScrollEventHandler在滚动时未返回NewValue

本文关键字:返回 NewValue 滚动 ScrollEventHandler 自定义 | 更新日期: 2023-09-27 18:29:47

有人能告诉我这里做错了什么吗。我基本上在自定义列表视图中创建了自己的滚动事件处理程序,这样我就可以获得更多的控制。调用OnScroll函数,但无论出于何种原因,NewValue始终为0,OldValue始终为-1。它没有正确更新的原因是什么?

public class ListViewXP : System.Windows.Forms.ListView
{        
 ...        
    [DllImport("user32.dll")]
    public static extern int GetScrollPos(IntPtr hWnd, int nBar);
    private const int SB_HORZ = 0;
    private const int SB_VERT = 1;
    public delegate void ScrollEventHandler(Object sender, ScrollEventArgs e);
    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 System.Windows.Forms.Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL)
        {
            int scrollPos = 0;
            if (m.Msg == WM_HSCROLL)
                scrollPos = GetScrollPos(this.Handle, SB_HORZ);
            else
                scrollPos = GetScrollPos(this.Handle, SB_VERT);
            OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), scrollPos));
        }
    }
    ..
}

    listView1.Scroll += new ListViewXP.ScrollEventHandler(listView1_OnScroll);
    private void listView1_OnScroll(object sender, ScrollEventArgs e)
    {
        Console.WriteLine(e.NewValue.ToString());
        Console.WriteLine(e.OldValue.ToString());
    }

自定义ScrollEventHandler在滚动时未返回NewValue

在WndProc中,您正在创建最终在listView1_OnScroll中使用的ScrollEventArgs对象。您将NewValue设置为0,而根本没有设置OldValue。

试试这样的东西:

protected override void WndProc(ref System.Windows.Forms.Message m)
{
    base.WndProc(ref m);
    if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL)
    {
        int scrollPos = 0;
        if (m.Msg == WM_HSCROLL)
          scrollPos = GetScrollPos(this.Handle, SB_HORZ);
        else
          scrollPos = GetScrollPos(this.Handle, SB_VERT);
        OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), scrollPos));
    }
}

如果您也想设置OldValue,则需要将NewValue存储为成员变量,并使用ScrollEventArgs的重载构造函数。