How to distinguish user vs programmatic changes in

2019-08-10 13:42发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

I have tried this and it worked.

        bool user_action = false;
        StackTrace stackTrace = new StackTrace();
        StackFrame[] stackFrames = stackTrace.GetFrames();
        foreach (StackFrame stackFrame in stackFrames)
        {
            if(stackFrame.GetMethod().Name == "WmMouseDown")
            {
                user_action = true;
                break;
            }
        }

        if (user_action)
        {
            MessageBox.Show("User");
        }
        else
        {
            MessageBox.Show("Code");
        }