Trigger event on trackbar ValueChanged, but not in code

我们两清 提交于 2019-12-22 10:59:53

问题


I want to be able to modify the value property of a trackbar in code without triggering my event handler. I wish to trigger the event only when the control is changed by the user by dragging the slider or moving it with the keyboard. What's the simplest way of achieving this?

I have 6 trackbars and I want to change the value of 3 of them depending on which trackbar is changed. The issue is that changing the value of those trackbars will trigger their ValueChanged events.


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/3506840/trigger-event-on-trackbar-valuechanged-but-not-in-code

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