c# - 防止在 Windows 窗体中使用鼠标滚轮滚动
问题描述
我想防止面板在使用鼠标滚轮时滚动。我尝试Handled
在HandledMouseEventArgs
to上设置标志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();
}
使用鼠标滚轮时,面板会滚动。如何防止它滚动?
解决方案
您需要创建自定义控件和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();
}
}
推荐阅读
- android - Metro Bundler internal 遇到内部错误
- django - Django & Celery,如果使用 venv,任务不会激活
- git - 是否可以为开发分支重写非常古老的 git 历史
- java - Elasticsearch 地理查询
- python - 使用日期时间设置函数来循环字典的值
- swagger - swagger 文件 - 标记字段为必填项和可选项
- aws-lambda - 如何使用 API 网关中的阶段变量通过无服务器框架指向不同的 lambda 函数
- google-analytics - mci通信服务公司 d/b/a verizon 业务
- sqoop - 批量降压插入 Sybase IQ
- sqlite - 显示 SQLite 的 raise 函数的错误信息?