views:

34

answers:

1

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.

A: 

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;
Andy