且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#winforms中设置轨道栏的invterval。

更新时间:2023-12-05 17:50:04

TrackBar的'Value属性从'MinimumValue到'MaximumValue是连续的。



要模拟棘爪(对齐值),你需要像这样实现TrackBar'ValueChanged EventHandler:
  private   int  smallChangeValue =  5 ; 
private int trackValue;
private bool blockRecursion = false ;

private void trackBar1_ValueChanged( object sender,EventArgs e)
{
if (blockRecursion) return 跨度>;

trackValue = trackBar1.Value;

if (trackValue%smallChangeValue!= 0
{
trackValue =(trackValue / smallChangeValue)* smallChangeValue;

// 请参阅下面的注释#1
blockRecursion = true
;

trackBar1.Value = trackValue;

blockRecursion = false ;
}

// 仅供调试
// textBox1.Text = trackValue.ToString();
} $ p $如果你检查一下这里发生了什么,你可以看到这只是做一个简单形式的TrackBar值的四舍五入(实际上是向下舍入)。



注意#1:在这个例子中,设置一个阻止递归的标志并不是必需的;显示这个的原因是为了你想要做一些更复杂的处理,例如:检查值的模数余数和小变化值,并且,如果它更接近下一个值,则进行四舍五入。

只需更改TickFrequency属性




How to set the interval for the track-bar in C# winforms instead of continuous numbers?

The pointer should jump to 1,5,10,15 instead of 1,2,3,4,5...15.

I have tried to set the SmallChange=5 in the Properties of TrackBar but it doesn't change the interval while dragging the pointer.

Can anyone please help to fix this problem?

The 'Value Property of the TrackBar is continuous from 'MinimumValue to 'MaximumValue.

To simulate detents (snap-to-values) you need to implement a TrackBar 'ValueChanged EventHandler like this:
private int smallChangeValue = 5;
private int trackValue;
private bool blockRecursion = false;

private void trackBar1_ValueChanged(object sender, EventArgs e)
{
    if (blockRecursion) return;

    trackValue = trackBar1.Value;

    if (trackValue % smallChangeValue  != 0)
    {
        trackValue = (trackValue / smallChangeValue) * smallChangeValue;

        // see note #1 below
        blockRecursion = true;

            trackBar1.Value = trackValue;

        blockRecursion = false;
    }

    // for debugging only
    // textBox1.Text = trackValue.ToString();
}

If you examine what's happening here, you can see this is just doing a simple form of rounding-off (rounding-down actually) of the TrackBar value.

note #1: in this example the setting a flag to block recursion is not really necessary; the reason this is shown is in case you want to do a bit more sophisticated handling such as: examining the modulo remainder of value and small-change value, and, in case it's closer to the next value, rounding-up.


just change TickFrequency properties