winforms 当光标位于datagridview的滚动条上时,如何禁用鼠标滚轮滚动?

cgh8pdjw  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(258)

我需要在数据网格视图中禁用鼠标滚轮(客户规范),目前我已经在派生的DataGridView类中尝试过

VerticleScrollBar.MouseWheel += WheelHandled;
MouseWheel += WheelHandled;

private void WheelHandled(object sender, MouseeventArgs e){
    HandledMouseEventArgs mouseWheelEvent = e as HandledMouseEventArgs;
    if(mouseWheelEvent != null){
        mouseWheelEvent.Handled = true;
    }
}

这阻止了滚轮在单元格内滚动,但如果光标在滚动条上,鼠标滚轮仍然可以工作,我不知道为什么。

4ioopgfo

4ioopgfo1#

如果不捕获受保护的VScrollBarWM_MOUSEWHEEL消息,就太晚了。在您的实现中,您可以订阅VScrollBar.MouseWheel事件,如下所示:

// The first control in the collection is HScrollBar.
// The second is VScrollBar.
var vs = dataGridView1.Controls[1] as VScrollBar;

vs.MouseWheel += (s, e) =>
{
    // ...
};

或者在你的派生类中:

public class DataGridViewEx : DataGridView
{
    public DataGridViewEx()
    {
        var vs = Controls[1] as VScrollBar;

        vs.MouseWheel += (s, e) =>
        {
            // ...
        };
    }
}

然而,处理事件设置(e as HandledMouseEventArgs).Handled = true;没有效果。同样,这样做已经太晚了。您需要在正确的时间采取行动。为此,您必须创建自定义DataGridView并将滚动条的本机窗口子类化,以防止处理WM_MOUSEWHEEL消息。

public class DataGridViewEx : DataGridView
{
    public DataGridViewEx()
    {
        new ScrollBarNativeWin(VerticalScrollBar);
        // If you need too
        // new ScrollBarNativeWin(HorizontalScrollBar);
    }

    private class ScrollBarNativeWin : NativeWindow
    {
        const int WM_MOUSEWHEEL = 0x020A;

        public ScrollBarNativeWin(ScrollBar scrollBar)
        {
            scrollBar.HandleCreated += (s, e) => AssignHandle(scrollBar.Handle);
            scrollBar.HandleDestroyed += (s, e) => ReleaseHandle();
        }

        protected override void WndProc(ref Message m)
        {                
            if (m.Msg != WM_MOUSEWHEEL) base.WndProc(ref m);
        }
    }
}

相关问题