1

When I add a trackbar to a form and set

    Me.TrackBar1.Minimum = 0
    Me.TrackBar1.Maximum = 100
    Me.TrackBar1.LargeChange = 10
    Me.TrackBar1.SmallChange = 10
    Me.TrackBar1.TickFrequency = 10

... the trackbar goes berzerk:

I can choose any small value by dragging the bar. The trackbar no longer sticks to values of 10, 20, 30, etc. I can manually choose any small value.

I confirmed this by adding the following code:

Private Sub TrackBar1_ValueChanged(sender As Object, e As EventArgs) Handles TrackBar1.ValueChanged

    Me.Text = Me.TrackBar1.Value

End Sub

Did I overlook anything in the docs, or is that bug in Framework 4.6.1?

tmighty
  • 10,734
  • 21
  • 104
  • 218

1 Answers1

1

I had no idea what you were asking in your question but after giving it some thought I finally figured out what it is you are asking. This is your question:

I can choose any small value by dragging the bar. The trackbar no longer sticks to values of 10, 20, 30, etc. I can manually choose any small value.

The documentation for SmallChange says:

When the user presses one of the arrow keys, the Value property changes according to the value set in the SmallChange property.

And the documentation for LargeChange says:

When the user presses the PAGE UP or PAGE DOWN key or clicks the track bar on either side of the scroll box, the Value property changes according to the value set in the LargeChange property.

Your Question Clarified

You are asking that instead of using the keyboard, if you are using the mouse, then the trackbar's value does not change as per the small and large change specified, which is 10 in your case. It actually steps up/down by 1's so it goes 1, 2, 3 and so on. But you want it to go 10, 20, 30 and so on.

Solution

You can handle the Scroll event and check if the value is a multiple of 10, if it is then do nothing. If not, change it by a multiple of 10.

VB.NET

Private Sub trackBar1_Scroll(ByVal sender As Object, ByVal e As EventArgs)
    Dim bar = CType(sender, TrackBar)
    Dim isMultipleOfTen As Boolean = bar.Value Mod bar.SmallChange = 0
    If isMultipleOfTen Then
        Return
    End If

    bar.Value = bar.SmallChange * ((bar.Value + bar.SmallChange / 2) / bar.SmallChange)
End Sub

C#

private void trackBar1_Scroll(object sender, EventArgs e)
{
    var bar = (TrackBar)sender;
    bool isMultipleOfTen = bar.Value % bar.SmallChange == 0;
    if (isMultipleOfTen)
    {
        return;
    }

    bar.Value = bar.SmallChange * ((bar.Value + bar.SmallChange / 2) / bar.SmallChange);
}
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
  • Thank you. Your code doesn't work perfectly, but now I know that I have to intercept "Scroll", thank you. If you want to improve your reply, please check SmallChange=10, LargeChange=10, Minimum=10,Maximum 100. First, it's not smooth (can't describe it any better), and at the rightmode slider value, an error is thrown (e. g. "105 exceeds the range"). – tmighty Dec 05 '17 at 20:09