C# Override an Event in Winforms [closed]

﹥>﹥吖頭↗ 提交于 2020-01-26 03:40:35

问题


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

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