How to ensure that adjusting a TrackBar control with a mouse will set values multiple of SmallChange and not any in between?

前端 未结 1 1893
粉色の甜心
粉色の甜心 2021-01-24 21:56

I used .Net trackbar control. My trackbar point is 0...5...10..15. Problem is, when user scrolled trackbar they easily drop scroll in between points. But i wan\'t to that user

相关标签:
1条回答
  • 2021-01-24 22:30

    You can simply force the Value property to be a multiple of the SmallChange property by overriding its value in an event handler for the ValueChanged event. Like this:

        private void trackBar1_ValueChanged(object sender, EventArgs e) {
            var bar = (TrackBar)sender;
            if (bar.Value % bar.SmallChange != 0) {
                bar.Value = bar.SmallChange * ((bar.Value + bar.SmallChange / 2) / bar.SmallChange);
            }
        }
    

    Note that this even works while the user is dragging the thumb with the mouse, like it behaves when he uses the keyboard. I assumed that's what you wanted.

    0 讨论(0)
提交回复
热议问题