简体   繁体   中英

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

I want to scroll ListView with mouse wheel while Ctrl button is pressed. But apparently pressing Ctrl changes scroll behavior: it stops scrolling, possibly tries to apply some zooming logic, I don't know. 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:

ListBox with WndProc override

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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