C# WinForms 阻止 TrackBar 滚动但允许垂直滚动
C# WinForms prevent TrackBar scrolling but allow vertical scrolling
当您在轨迹栏上使用滚轮时,它会更改轨迹栏值。我真的不喜欢这种行为,所以我想禁用它。我在这里找到了一个简单的解决方案:
但问题是,只要鼠标悬停在轨迹栏上,这将阻止任何垂直滚动的发生。有没有办法允许垂直滚动但阻止轨迹栏滚动?
您可以将 TrackBar 子类化,然后将鼠标滚轮消息转发到它的父容器。
与此答案中的想法相同:
// Subclass of TrackBar
public class TrackBarWithParentMouseWheel : TrackBar
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
private const int WM_MOUSEWHEEL = 0x020A;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_MOUSEWHEEL)
{
SendMessage(this.Parent.Handle, m.Msg, m.WParam, m.LParam);
m.Result = IntPtr.Zero;
}
else base.WndProc(ref m);
}
}
// Form.Designer.cs
this.trackBar1 = new TrackBarWithParentMouseWheel(); // in InitializeComponent()
private TrackBarWithParentMouseWheel trackBar1; // instead of private System.Windows.Forms.TrackBar trackBar1;
当您在轨迹栏上使用滚轮时,它会更改轨迹栏值。我真的不喜欢这种行为,所以我想禁用它。我在这里找到了一个简单的解决方案:
但问题是,只要鼠标悬停在轨迹栏上,这将阻止任何垂直滚动的发生。有没有办法允许垂直滚动但阻止轨迹栏滚动?
您可以将 TrackBar 子类化,然后将鼠标滚轮消息转发到它的父容器。
与此答案中的想法相同:
// Subclass of TrackBar
public class TrackBarWithParentMouseWheel : TrackBar
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
private const int WM_MOUSEWHEEL = 0x020A;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_MOUSEWHEEL)
{
SendMessage(this.Parent.Handle, m.Msg, m.WParam, m.LParam);
m.Result = IntPtr.Zero;
}
else base.WndProc(ref m);
}
}
// Form.Designer.cs
this.trackBar1 = new TrackBarWithParentMouseWheel(); // in InitializeComponent()
private TrackBarWithParentMouseWheel trackBar1; // instead of private System.Windows.Forms.TrackBar trackBar1;