C# 覆盖 Winforms 中的事件 [英] C# Override an Event in Winforms
问题描述
我需要为 C# winforms 应用程序中的所有文本框添加一个事件.
I need to add an Event for all my Textboxes in a C# winforms app.
我如何覆盖例如 Enter
事件,以便默认情况下所有文本框都具有此事件?提前致谢
How can I override for example, the Enter
event so all textboxes will have by default this event ?
Thanks in advance
推荐答案
您可以从 TextBox
继承 YourTextBox
并覆盖 OnEnter
方法以提供所有此类文本框的默认行为.然后使用这个控件代替默认的 TextBox
控件:
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);
}
}
或者您可以将所有文本框订阅到相同的事件处理程序.您可以手动或以编程方式执行此操作.例如.如果您只对 Form 的顶级文本框感兴趣:
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;
这篇关于C# 覆盖 Winforms 中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!