【问题标题】:TextBox RaiseEvent KeyDownEvent does not work ... ( code attached )TextBox RaiseEvent KeyDownEvent 不起作用...(附代码)
【发布时间】:2010-12-15 10:37:37
【问题描述】:

试图将事件提升到文本框 - 但我没有在文本框文本中看到键值。 我可以看到文本框事件“OnKeyDownEvent”在断点处停止 - 但我不明白为什么 KeyEventArgs ( Key.D0 ) 的文本没有插入到文本框文本中。

代码:

if( currentTextBoxInFocus != null )
{
    KeyEventArgs k = new KeyEventArgs( Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, System.Environment.ProcessorCount, Key.D0 );
    //KeyEventArgs k = new KeyEventArgs( Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.D0 );
    k.RoutedEvent = UIElement.KeyDownEvent;
    currentTextBoxInFocus.RaiseEvent( k );
    k.RoutedEvent = UIElement.KeyUpEvent;
    currentTextBoxInFocus.RaiseEvent( k );
}

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您正在尝试使用 Key 事件作为输入源,而它们实际上用于指示来自操作系统的键盘输入的结果。这些事件不会导致将文本添加到 TextBox。相反,它们指示键盘输入何时输入到控件(如 TextBox)中。

    如果您想模拟从代码中输入文本框,只需将所需的文本添加到 Text 属性中:

    int caret = currentTextBoxInFocus.CaretIndex;
    currentTextBoxInFocus.Text = String.Format("{0}0{1}", currentTextBoxInFocus.Text.Substring(0, caret), currentTextBoxInFocus.Text.Substring(currentTextBoxInFocus.CaretIndex));
    currentTextBoxInFocus.CaretIndex = caret + 1;
    

    【讨论】:

      猜你喜欢
      • 2012-09-15
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 2017-04-11
      相关资源
      最近更新 更多