WinRT KeyDown fired twice when Enter is pressed

I have noticed a very unusual oddity which occurs when handling the KeyDown event. When the user hits the ‘Enter’ key, the event is actually fired twice (at least this is the case for TextBox  and PasswordBox  controls on which I have noticed this behavior).

Consider the following code snippet:

private void TextBox_KeyDown( object sender, KeyRoutedEventArgs e )
    if ( e.Key == VirtualKey.Enter )
        Frame.Navigate( typeof( SomeOtherPage ) );

What will actually happen when the user actually presses the ‘Enter’ key in the TextBox ?

As you would expect, the event is fired first time and frame navigates to SomeOtherPage . But right after the execution of the handler finishes, it is called once again with the exact same arguments! The code will get executed again and the frame will once again navigate – which is (probably) not what you actually needed!

This behavior is really connected only with the ‘Enter’ key and it does not seem to be present for other keyboard keys. Luckily the workaround is simple:

private void TextBox_KeyDown( object sender, KeyRoutedEventArgs e )
    if ( e.Key == VirtualKey.Enter )
        Frame.Navigate( typeof( SomeOtherPage ) );
        e.Handled = true;

By setting KeyRoutedEventArgs ‘ Handled Property to true we are essentially stopping subsequent bubbling of the event higher up the tree, but this also prevents the event to fire again on the same control.

I have reported this issue in the Windows Feedback app for Developer Platform. If you want to support its resolution in future versions of UWP, vote for it by clicking here.

Buy me a coffeeBuy me a coffee

3 thoughts on “WinRT KeyDown fired twice when Enter is pressed”

  1. Wonderful, so it wasnt just me then, I was about to go insane about this, but your solution solved it for me. Thanks! 🙂

    1. Great it helped 🙂 . In Windows 10, this can be even set up to work automatically, I have updated the article with this information.

      1. Under UWP windows 10 App , events will still fired multiple times,
        Example, mediaElement state changed events will fired more than 2 times, e.handled property are not available,
        You need to handle the multiple firing, yourself.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


This site uses Akismet to reduce spam. Learn how your comment data is processed.