views:

36

answers:

2

I have logic on a CheckBox's OnCheckedChanged event that fires on form load as well as when user changes check state. I want the logic to only execute upon user action.

Is there a slick way of detecting user vs programmatic change that doesn't rely on setting/checking user variables?

A: 

Try some good old reflection?

StackFrame lastCall = new StackFrame(3);
if (lastCall.GetMethod().Name != "OnClick")
{
    // Programmatic Code
}
else
{
    // User Code
}

The Call Stack Goes like this:

  • OnClick
  • set_Checked
  • OnCheckChanged

So you need to go back 3 to differentiate who SET Checked

Do remember though, there's some stuff that can mess with the call stack, it's not 100% reliable, but you can extend this a bit to search for the originating source.

Aren
A: 

I usually have a bool flag on my form that I set to true before programmatically changing values. Then the event handler can check that flag to see if it is a user or programmatic.

tster
cs31415 asked for a solution that didn't involve setting a 'user variable'
Aren