Peter C
Peter C

Reputation: 23

UWP Enter key press not detected

I am trying to detect key presses in my c# uwp application but the enter key press event is not being triggered. I have added the KeyUp event to the main window and the event is triggered for all keyboard keys except for the enter and space bar keys. Any ideas on how to detect the enter key? The line I added to detect key presses in the XAML in the tags is KeyUp="MainPg_KeyUp"

Upvotes: 1

Views: 2415

Answers (2)

Vignesh
Vignesh

Reputation: 1882

KeyDown event will not trigger system handled keys. You will have to use PreviewKeyDown event.

https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.uielement.previewkeydown

<TextBox PreviewKeyDown="eventhandler"/>

 private void eventhandler(object sender, KeyRoutedEventArgs e)
 {
     if(e.Key == VirtualKey.Enter)
     {
     }
 }

Upvotes: 0

Ryan Thiele
Ryan Thiele

Reputation: 364

I would use Keyboard Accelerators. For example, I want to invoke a button click when the user hits the Enter key. The code would be:

<Button Content="Invoke Me!">
    <Button.KeyboardAccelerators>
        <KeyboardAccelerator Key="Enter" />
    </Button.KeyboardAccelerators>
</Button>

You can also use modifiers like alt, ctrl, or shift as well as the key like so:

<Button Content="Save">
    <Button.KeyboardAccelerators>
        <KeyboardAccelerator Key="S" Modifiers="Control" />
    </Button.KeyboardAccelerators>
</Button>

You can place these on the page level as well, but you will have to place an event handler in the code behind. Here is more information about key board acceleration.

Upvotes: 1

Related Questions