Reputation: 179
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);
}
Upvotes: 5
Views: 3644
Reputation: 131
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.
Upvotes: 3
Reputation: 1627
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>
Upvotes: 1