防止在 Windows 窗体中使用鼠标滚轮滚动

LTR*_*LTR 5 .net c# scroll mousewheel winforms

我想防止面板在使用鼠标滚轮时滚动。我尝试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();
}
Run Code Online (Sandbox Code Playgroud)

使用鼠标滚轮时,面板会滚动。我怎样才能阻止它滚动?

sty*_*tyx 8

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

所以首先创建一个新面板

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

编辑,或者如果您想控制是否可滚动(然后在主面板中您可以调用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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后以原来的形式使用它

        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();
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • “WParam”设置为“IntPtr.Zero”将更改载体内容,表示*没有发生轮子旋转*。`m.Result = IntPtr.Zero` 是该消息处理后的标准结果。让“base.WndProc”通过会保留“lParam”引用的鼠标位置。 (2认同)