Search code examples
c#timerintervalstrackbar

Timer interval not adjusting with Trackbar progress


I'm trying to allow the user to control the interval of a timer runClick by use of a trackbar trackbartimer

When the user slides right, the timer is supposed to speed up and when left, vice versa; but that's not the case.

Here's what I've attempted:

private void runClick_Tick(object sender, EventArgs e)
    {
      runClick.Interval = trackbartimer.Value;
    }


    private void trackbartimer_Scroll(object sender, EventArgs e)
    {
        trackbartimer.Minimum = 1000;
        trackbartimer.Maximum = 1;
        trackbartimer.TickFrequency = 10;
        trackbartimer.LargeChange = 100;
        trackbartimer.SmallChange = 10;

        runClick.Interval = trackbartimer.Value;

    }

Can anyone show me where I'm going wrong?


Solution

  • The problem is that moving the thumb to the Right on the TrackBar increases the value and therefore the interval and vice versa. Setting the Max to 1 and Min to 1000 does not invert the control's logic. If you enter those values via the IDE you'll see it fix the values rather than use an 'inverted' range.

    Also, the timer is not so accurate that there will be much change in the speed below 55 or 60 ms, nor will it fire precisely at the interval you specify. From MSDN:

    The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds.

    The simplest thing is to put some << Faster and Slower >> labels on the form, but to make it go faster to the right use some simple math:

    private void trackBar1_ValueChanged(object sender, EventArgs e)
    {
        int v = (trackBar1.Maximum - trackBar1.Value) + 100;
    
        timer1.Interval = v;
    }
    

    The +100 is to avoid a crazy-fast interval.

    I would use the ValueChanged event to process far fewer events, and there is no need to reset the timer interval again (and again) in the Tick event.