如何以通用方式向所有TextBox声明KeyPress事件处理程序?

问题描述

| 我有20个文本框形式。我为所有这些文本框都有一个通用的KeyPress事件。 因此,我尝试按以下方式声明keypress事件:是否可能?
for (int Cnl = 1; Cnl < 21; Cnl++)
{
   ((RichTextBox)Cnl).KeyPress += new KeyPressEventHandler(this.Comn_KeyPress);
}
    

解决方法

正确的想法;但是将int转换为RichTextBox将永远无法工作。尝试这个:
 foreach (var control in this.Controls)
 {
     var text = control as RichTextBox;
     if (text != null)
          text.KeyPress += new KeyPressEventHandler(this.Comn_KeyPress);
 }
    ,对于WPF应用程序,您可以使用EventManager静态类上的方法注册全局事件处理程序:
// Register the following class handlers for the TextBox XxFocus events.
EventManager.RegisterClassHandler(typeof(TextBox),TextBox.GotKeyboardFocusEvent,new RoutedEventHandler(HandleTextBoxFocus));
然后在事件处理程序上添加所需的任何逻辑,例如:
    private void HandleTextBoxFocus(Object sender,RoutedEventArgs e)
    {
        (sender as TextBox).SelectAll();
    }
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...