Trigger event on trackbar ValueChanged, but not in code

左心房为你撑大大i 提交于 2019-12-06 00:19:06

One way you can do this is to temporarily remove the event handlers before you modify the values in code, and then reattach them afterwards, although this doesn't seem too elegant.

Alternatively you could create your own custom TrackBar class that inherits from TrackBar and override the OnValueChanged() method to do what you want.

If you did this, an idea I can think of is to set a SuspendChangedEvents property before changing the value, and reset it afterwards, This would provide similar functionality to the 'remove/attach' handler technique but the logic is encapsulated within the TrackBar itself.

public class MyTrackBar : TrackBar
{
    public bool SuspendChangedEvent
    { get; set; }

    protected override void OnValueChanged(EventArgs e)
    {
        if (!SuspendChangedEvent) base.OnValueChanged(e);
    }
}

Then in your code you can do something like this.

// Suspend trackbar change events
myTrackBar1.SuspendChangedEvents = true;

// Change the value
myTrackBar1.Value = 50;  // ValueChanged event will not fire.

// Turn changed events back on
myTrackBar1.SuspendChangedEvents = false;

You could use the Scroll event instead of ValueChanged, this event only gets fired when the user drags the slider or uses the keys to move its value, and the changes you make from the code won't fire it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!