开发者

How to distinguish user vs programmatic changes in WinForms CheckBox?

开发者 https://www.devze.com 2022-12-30 00:52 出处:网络
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 ex开发者_开发知识库ecute upon user action.

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 ex开发者_开发知识库ecute upon user action.

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


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.


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.


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");
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消