How to distinguish user vs programmatic changes in WinForms CheckBox?

自古美人都是妖i 提交于 2019-12-11 06:40:01

问题


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


来源:https://stackoverflow.com/questions/2806601/how-to-distinguish-user-vs-programmatic-changes-in-winforms-checkbox

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