问题
I need to add an Event for all my Textboxes in a C# winforms app.
How can I override for example, the Enter
event so all textboxes will have by default this event ?
Thanks in advance
回答1:
You can inherit YourTextBox
from TextBox
and override OnEnter
method to provide default behavior for all such textboxes. Then use this control instead of default TextBox
controls:
public class YourTextBox : TextBox
{
protected override void OnEnter(EventArgs e)
{
// do something here
base.OnEnter(e);
}
}
Or you can subscribe all textboxes to same event handler. You can do that either manually, or programmatically. E.g. if you are interested only in top-level textboxes of Form:
foreach (var textBox in Controls.OfType<TextBox>())
textBox.Enter += YourEventHandler;
来源:https://stackoverflow.com/questions/43668106/c-sharp-override-an-event-in-winforms