How to distinguish user vs programmatic changes in WinForms CheckBox?
Asked Answered
K

3

1

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?

Kacikacie answered 10/5, 2010 at 21:33 Comment(0)
M
0

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.

Manasseh answered 10/5, 2010 at 21:45 Comment(1)
cs31415 asked for a solution that didn't involve setting a 'user variable'Ezar
E
0

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.

Ezar answered 10/5, 2010 at 21:42 Comment(0)
M
0

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.

Manasseh answered 10/5, 2010 at 21:45 Comment(1)
cs31415 asked for a solution that didn't involve setting a 'user variable'Ezar
E
0

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");
        }
Extravagant answered 16/11, 2010 at 14:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.