5

I am trying to simulate a key press in a button event. I can use the code below to simulate some keys such as Backspace, but the Enter is not working.

What am I doing wrong?

private void btnEnter_Click(object sender, RoutedEventArgs e)
{
    tbProdCode.Focus();

    KeyEventArgs ke = new KeyEventArgs(
        Keyboard.PrimaryDevice,
        Keyboard.PrimaryDevice.ActiveSource,
        0,
        Key.Enter)
    {
        RoutedEvent = UIElement.KeyDownEvent
    };

    InputManager.Current.ProcessInput(ke);
}
Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
justinfly
  • 179
  • 2
  • 6
  • Something tells me what it is executed too early, not when `tbProdCode` gets focus. Try to put part after setting focus inside `Dispatcher.Invoke(() => { ... });`. If it's not the case, then can you please explain what exactly is not working? You have button and textbox, when button is pressed textbox should get focus and ... ? – Sinatr Nov 23 '15 at 15:40
  • I found the problem. Because I used the PreviewKeyDown for btnEnter instead of KeyDown. – justinfly Nov 24 '15 at 07:32

2 Answers2

3

I've tried your code, and I can simulate the Enter perfectly.

You've not stated what you wish Enter to do in your textbox, so i'm going to go out on a limb here and assume you want to go to the next line - as that is one of the most common reasons to use Enter in a textbox

For that to work, you need to set AcceptsReturn="True" in Xaml - this allows the textbox to accept the Enter Key.

<TextBox x:Name="tbProdCode" AcceptsReturn="True" />

If that functionality is not what you want, then you likely don't have an event wired up to do something when Enter is hit.

Jamie P
  • 131
  • 9
  • Might I suggest also putting your `KeyEventArgs ke = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key) { RoutedEvent = UIElement.KeyDownEvent }; InputManager.Current.ProccessInput(ke)` into it's own function where you pass in a key. i.e. `SendKey(Key key)`. – Jamie P Nov 23 '15 at 16:11
1

Another way to approach this is by using Xaml to bind the key press to a command:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="Enter" Command="{Binding DoSomething}"/>
    </TextBox.InputBindings>
</TextBox>
Ryan Searle
  • 1,597
  • 1
  • 19
  • 30