1

When you use the scroll wheel over a track bar, it changes the track bar value. I really don't like this behavior so I want to disable it. I found an easy solution here: https://stackoverflow.com/a/34928925

But the problem is this will prevent any vertical scrolling to happen whenever the mouse is over a track bar. Is there any way to allow vertical scrolling but prevent track bar scrolling?

midorisalt
  • 13
  • 3
  • Can't you check in the `sender` to see over which type of object it's happening? Or else, using the `MouseWheel` event on the TrackBar control? – Andrew Apr 11 '22 at 14:15

1 Answers1

1

You can subclass the TrackBar then forward the mouse wheel messages to it's parent container.
Same idea as in this answer:
https://stackoverflow.com/a/57144200/2983568

// 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;
evilmandarine
  • 4,241
  • 4
  • 17
  • 40
  • Thank you that works. Is there a good way to use this custom class in a program designed in visual studio with the winforms designer? – midorisalt Apr 11 '22 at 15:13
  • If you mean adding it to the toolbox, take a look [at this question](https://stackoverflow.com/a/8931414/2983568). Also please consider accepting the answer if that is ok :) – evilmandarine Apr 11 '22 at 15:35