Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating the Enter key in WPF

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);
}
like image 760
justinfly Avatar asked Sep 26 '22 03:09

justinfly


2 Answers

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.

like image 135
Jamie P Avatar answered Oct 11 '22 16:10

Jamie P


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>
like image 39
Ryan Searle Avatar answered Oct 11 '22 18:10

Ryan Searle