Tips and tricks for C# Metro developers : Handling the keyboard events

I have some users that ask me how can I handle the keyboard ? Should I add an event Handler on a top root grid?

The response is no Sourire. The better solution is to use the KeyUp/KeyDown event of the CoreWindow which is able to catch all the keyboard strokes:

protected override void OnNavigatedTo(NavigationEventArgs e)
    Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp;

void CoreWindow_KeyUp(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
    switch (args.VirtualKey)
        case Windows.System.VirtualKey.Number1:
        case Windows.System.VirtualKey.Number2:

} } protected override void OnNavigatedFrom(NavigationEventArgs e) { Window.Current.CoreWindow.KeyUp -= CoreWindow_KeyUp; }

Please note that the KeyEventArgs class provides a Handled property in order to stop the propagation of the event.

Comments (2)

  1. appdeveloper says:

    my god after 4 hours of research this small piece of code worked for me :)

  2. Eugene says:

    Thank you! I have just spent a couple of hours on this until I found your post :)