How to distinguish user and software changes in WinForms CheckBox?

I have logic in the CheckBox OnCheckedChanged event, which fires when the form loads, as well as when checking the status of the user. I want the logic to be executed only with user action.

Is there a slick way to detect custom programmatic changes that are independent of setting / checking custom variables?

+1
source share
3 answers

I usually have a bool flag in my form that I set to true before changing the values โ€‹โ€‹programmatically. The event handler can then check this flag to see if it is a user or software.

0
source

Try a good old reflection?

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

The call column is as follows:

  • Onclick
  • set_Checked
  • Oncheckchanged

So you need to go back 3 to distinguish who SET is installed

Remember that there is something that can go wrong with the call stack, it is not 100% reliable, but you can expand this bit a bit to find the source.

0
source

I 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
source

Source: https://habr.com/ru/post/1402356/


All Articles