簡體   English   中英

Windows 窗體:ctrl 按鈕可防止 ListView 使用鼠標滾輪滾動

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

我想在按下 Ctrl 按鈕的同時用鼠標滾輪滾動 ListView。 但顯然按下 Ctrl 會改變滾動行為:它停止滾動,可能會嘗試應用一些縮放邏輯,我不知道。 我不知道如何覆蓋它。 請任何幫助或建議?

在按住 Ctrl 鍵時讓鼠標滾輪滾動的解決方案是偵聽WndProc事件並專門檢測MOUSEWHEEL觸發器,最小的簡單工作示例:

帶有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;
            }
        }
    }
}

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

然后終於測試了

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