You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁用DataGridView滚动条上的鼠标滚轮滚动功能?

解决DataGridView鼠标滚轮禁用问题(含滚动条区域)

问题原因

你当前代码存在两个关键问题:

  1. 拼写错误:VerticleScrollBar应为VerticalScrollBar,导致滚动条的MouseWheel事件未正确绑定
  2. DataGridView的内置滚动条是动态创建的子控件,仅在构造函数中绑定事件无法捕获到实际的滚动条实例

修正后的实现方案

在派生的DataGridView类中,通过以下方式彻底禁用鼠标滚轮(包括滚动条区域):

public class NoScrollDataGridView : DataGridView
{
    public NoScrollDataGridView()
    {
        // 绑定自身的MouseWheel事件
        MouseWheel += WheelHandled;
    }

    // 重写OnControlAdded,捕获动态创建的滚动条控件
    protected override void OnControlAdded(ControlEventArgs e)
    {
        base.OnControlAdded(e);
        // 处理垂直滚动条
        if (e.Control is VScrollBar vScrollBar)
        {
            vScrollBar.MouseWheel -= WheelHandled;
            vScrollBar.MouseWheel += WheelHandled;
        }
        // 如需禁用水平滚动条滚轮,可添加以下逻辑
        else if (e.Control is HScrollBar hScrollBar)
        {
            hScrollBar.MouseWheel -= WheelHandled;
            hScrollBar.MouseWheel += WheelHandled;
        }
    }

    private void WheelHandled(object sender, MouseEventArgs e)
    {
        if (e is HandledMouseEventArgs handledArgs)
        {
            handledArgs.Handled = true;
        }
    }

    // 重写OnMouseWheel,彻底拦截控件自身的滚轮逻辑
    protected override void OnMouseWheel(MouseEventArgs e)
    {
        if (e is HandledMouseEventArgs handledArgs)
        {
            handledArgs.Handled = true;
        }
        // 不调用基类方法,避免执行默认滚动逻辑
    }
}

方案说明

  • OnControlAdded重写:DataGridView的滚动条会在初始化或布局变化时动态生成,通过这个方法能确保捕获到所有滚动条子控件并绑定事件
  • 事件去重绑定:先移除再添加事件,避免重复绑定导致多次触发
  • OnMouseWheel重写:直接拦截控件自身的滚轮事件,且不调用基类方法,彻底阻止默认滚动行为

内容的提问来源于stack exchange,提问作者jneko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 07:32:36