简体   繁体   English

Windows 窗体:ctrl 按钮可防止 ListView 使用鼠标滚轮滚动

[英]Windows Forms: ctrl button prevents ListView from scrolling with mouse wheel

I want to scroll ListView with mouse wheel while Ctrl button is pressed.我想在按下 Ctrl 按钮的同时用鼠标滚轮滚动 ListView。 But apparently pressing Ctrl changes scroll behavior: it stops scrolling, possibly tries to apply some zooming logic, I don't know.但显然按下 Ctrl 会改变滚动行为:它停止滚动,可能会尝试应用一些缩放逻辑,我不知道。 And I can't find out how to override that.我不知道如何覆盖它。 Please any help or suggestions?请任何帮助或建议?

The solution to get mouse wheel scrolling working while Ctrl key is held down is to listen for the WndProc event and specifically detecting MOUSEWHEEL trigger, minimum simple working example:在按住 Ctrl 键时让鼠标滚轮滚动的解决方案是侦听WndProc事件并专门检测MOUSEWHEEL触发器,最小的简单工作示例:

ListBox with WndProc override带有WndProc覆盖的列表框

class CtrlListBoxScroll : ListBox
{
    private const int WM_HSCROLL = 0x114;
    private const int WM_VSCROLL = 0x115;
    private const int WM_MOUSEWHEEL = 0x20A;

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_MOUSEWHEEL)
        {
            var scrollDirection = NativeMethods.GET_WHEEL_DELTA_WPARAM(m.WParam);
            // scrolling down
            if (this.TopIndex < this.Items.Count && scrollDirection < 0)
            {
                this.TopIndex += 1;
            }
            // scrolling up
            if (this.TopIndex > 0 && scrollDirection > 0)
            {
                this.TopIndex -= 1;
            }
        }
    }
}

NativeMethods to read the wParam and detect scroll direction读取 wParam 并检测滚动方向的 NativeMethods

internal static class NativeMethods
{
    internal static ushort HIWORD(IntPtr dwValue)
    {
        return (ushort)((((long)dwValue) >> 0x10) & 0xffff);
    }

    internal static ushort HIWORD(uint dwValue)
    {
        return (ushort)(dwValue >> 0x10);
    }

    internal static int GET_WHEEL_DELTA_WPARAM(IntPtr wParam)
    {
        return (short)HIWORD(wParam);
    }

    internal static int GET_WHEEL_DELTA_WPARAM(uint wParam)
    {
        return (short)HIWORD(wParam);
    }
}

Then finally testing it然后终于测试了

private void Form1_Load(object sender, EventArgs e)
{
    var ctrlListBoxScroll = new CtrlListBoxScroll();
    ctrlListBoxScroll.Items.AddRange
    (
        new object[]
        {
            "hello", "scroll", "bar", "pressing", "ctrl", "to scroll",
            "this", "list", "box", "check", "ctrl", "key", "is", "held"
        }
    );
    this.Controls.Add(ctrlListBoxScroll);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM