Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# TextBox RaiseEvent KeyDownEvent不工作。。。(附代码)_C#_Wpf - Fatal编程技术网

C# TextBox RaiseEvent KeyDownEvent不工作。。。(附代码)

C# TextBox RaiseEvent KeyDownEvent不工作。。。(附代码),c#,wpf,C#,Wpf,试图将事件提升到textBox-但我在textBox文本中看不到键值。 我可以看到textbox事件“OnKeyDownEvent”在断点处停止-但我不理解为什么KeyEventArgs(Key.D0)的文本没有插入到textbox文本中 守则: if( currentTextBoxInFocus != null ) { KeyEventArgs k = new KeyEventArgs( Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.Ac

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

守则:

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 );
}

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

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

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;