如何以通用方式向所有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();
    }