How to determine if an event was triggered by a user action or code?

I have a bunch of controls on the form, and all their “change” events point to the same event handler. Some of them are: txtInput1 TextChanged , chkOption1 CheckedChanged, and cmbStuff1 SelectedIndexChanged . Here is the event handler:

private void UpdatePreview(object sender, EventArgs e) { // TODO: Only proceed if event was fired due to a user clicking/typing, not a programmatical set if (sender.IsSomethingThatTheUserDid) // .IsSomethingThatTheUserDid doesn't work { txtPreview.Text = "The user has changed one of the options!"; } } 

I would like the if statement to be executed only when the user changes the text of the TextBox or clicks the checkbox or something else. I do not want this to happen if the text or check box was changed by any other part of the program.

+3
c # events
source share
2 answers

There is no built-in mechanism for this. However, you can use the flag.

 bool updatingUI = false; private void UpdatePreview(object sender, EventArgs e) { if (updatingUI) return; txtPreview.Text = "The user has changed one of the options!"; } 

Then, when you update the user interface from your code:

 updatingUI = true; checkBox1.Checked = true; updatingUI = false; 

If you want to override the solution, you can use something like this:

 private void UpdateUI(Action action) { updatingUI = true; action(); updatingUI = false; } 

And use it as follows:

 UpdateUI(()=> { checkBox1.Checked = true; }); 
+9
source share

Can't you just check the sender? If it calls from a wired event into a user interface control, it will return with the control. If you fire the event from code, it will either be the component making the call, or you can do anything:

 private void SomewhereElse() { UpdatePreview(null, new EventArgs()); } private void UpdatePreview(object sender, EventArgs e) { if (sender == null) { txtPreview.Text = "The user has changed one of the options!"; } } 

or you can do it:

 private void UpdatePreview(object sender, EventArgs e) { if (!(sender is Control)) { txtPreview.Text = "The user has changed one of the options!"; } } 
-one
source share

All Articles