Reputation: 21
I want to prevent scrolling with the mousewheel in a panel with a scrollbar, how can ido this?
I have seen this suggested, but it's not working:
panel.MouseWheel += new MouseEventHandler(MouseWheel);
void MouseWheel(object sender, MouseEventArgs e) {
((HandledMouseEventArgs)e).Handled = true;
}
Upvotes: 2
Views: 2613
Reputation: 1
chatGPT helped me. Use NativeWindow.
using System;
using System.Windows.Forms;
public class MyForm : Form
{
private Panel myPanel;
private PanelNoScrollNativeWindow noScrollWindow;
public MyForm()
{
myPanel = new Panel();
myPanel.Dock = DockStyle.Fill;
myPanel.AutoScroll = true;
// Add some content to the panel
for (int i = 0; i < 20; i++)
{
var label = new Label
{
Text = $"Label {i + 1}",
AutoSize = true,
Location = new System.Drawing.Point(10, i * 30)
};
myPanel.Controls.Add(label);
}
// Subclass the panel's window procedure
noScrollWindow = new PanelNoScrollNativeWindow(myPanel);
this.Controls.Add(myPanel);
this.Text = "No Scroll Panel Example";
this.Size = new System.Drawing.Size(300, 300);
}
// NativeWindow class to handle the panel's window procedure
private class PanelNoScrollNativeWindow : NativeWindow
{
private const int WM_MOUSEWHEEL = 0x020A;
public PanelNoScrollNativeWindow(Control control)
{
AssignHandle(control.Handle);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_MOUSEWHEEL)
{
// Suppress the mouse wheel message
return;
}
base.WndProc(ref m);
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
Upvotes: 0
Reputation: 81675
Try inheriting your own Panel and just comment out the OnMouseWheel call:
public class WheelessPanel : Panel {
protected override void OnMouseWheel(MouseEventArgs e) {
// base.OnMouseWheel(e);
}
}
Upvotes: 5
Reputation: 7344
If you provide a user with a scrollable control, why would you then prevent them from scrolling it? If you don't want them to scroll, don't give them scroll bars.
If I came across a UI like that I would dislike it and only use it if I absolutely had to.
Upvotes: -3