首页 > 解决方案 > 防止在 Windows 窗体中使用鼠标滚轮滚动

问题描述

我想防止面板在使用鼠标滚轮时滚动。我尝试HandledHandledMouseEventArgsto上设置标志false,但这不起作用。

在这个重现代码中,我们有一个面板和一个按钮。

using (var scrollTestForm=new Form())
{
    var panel = new Panel() { Dock = DockStyle.Fill };
    scrollTestForm.Controls.Add(panel);
    var buttonOutsideArea = new Button();
    buttonOutsideArea.Location = new System.Drawing.Point(panel.Width * 2, 100);
    panel.Controls.Add(buttonOutsideArea);
    panel.AutoScroll = true;
    panel.MouseWheel += delegate (object sender, MouseEventArgs e)
    {
        ((HandledMouseEventArgs)e).Handled = false;
    };
    scrollTestForm.ShowDialog();
}

使用鼠标滚轮时,面板会滚动。如何防止它滚动?

标签: c#.netwinformsscrollmousewheel

解决方案


您需要创建自定义控件和WM_MOUSEWHEEL 消息

所以首先新建一个面板

    public class PanelUnScrollable : Panel
    {       
        protected override void WndProc(ref Message m)
        {           
            if(m.Msg == 0x20a) return; 
            base.WndProc(ref m);
        }
    }

编辑,或者如果你想控制是否可滚动(然后在你的主面板中你可以调用panel.ScrollDisabled = true);

    public class PanelUnScrollable : Panel
    {
        public bool ScrollDisabled { get; set; }
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x20a && ScrollDisabled) return;             
            base.WndProc(ref m);
        }
    }

然后以原始形式使用它

        public Form2()
        {
            InitializeComponent();

            CreateNewUnscrollablePanel();            
        } 

        public void CreateNewUnscrollablePanel()
        {
           using (var unScrollablePanel = new UnScrollablePanel() { Dock = DockStyle.Fill })
            {                     
                this.Controls.Add(unScrollablePanel);
                var buttonOutsideArea = new Button();
                buttonOutsideArea.Location = new System.Drawing.Point(unScrollablePanel.Width * 2, 100);
                unScrollablePanel.Controls.Add(buttonOutsideArea);
                unScrollablePanel.AutoScroll = true;
                unScrollablePanel.ScrollDisabled = true; //-->call the panel propery
                unScrollablePanel.MouseWheel += delegate(object sender, MouseEventArgs e) //--> you dont need this
                {
                    ((HandledMouseEventArgs)e).Handled = true;
                };

                this.ShowDialog();
            }
        }

推荐阅读