Reputation: 1352
I want to prevent a panel from scrolling when the mousewheel is used. I've tried setting the flag Handled
on the HandledMouseEventArgs
to false
, but that doesn't work.
In this repro code, we have one panel and one button.
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();
}
When using the mouse wheel, the panel scrolls. How can I prevent it from scrolling?
Upvotes: 5
Views: 2931
Reputation: 1917
You need to create your custom control and WM_MOUSEWHEEL message
So first create a new panel
public class PanelUnScrollable : Panel
{
protected override void WndProc(ref Message m)
{
if(m.Msg == 0x20a) return;
base.WndProc(ref m);
}
}
Edit, or if you want to control is scrollable or not(and then in your main panel you can call 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);
}
}
Then use it in your original form
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();
}
}
Upvotes: 8