Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keydown Event fires twice

On a Windows store App, I have this simple TextBox

<TextBox Name="TextBoxUser" HorizontalAlignment="Right" Width="147" Margin="20,0,0,0" KeyDown="TextBox_KeyDown" /

That has a KeyDown Event associated with it.

        private async void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Enter)
        {
           Debug.WriteLine("LA");
        }
    }

And the output of this function is:


LA
LA

although I press Enter only once, it prints 2 times. Any reason for that or am I doing something wrong?

like image 413
Thought Avatar asked Feb 25 '14 11:02

Thought


People also ask

What is the difference between the Keydown and Keyup events?

The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.

Should I use Keydown or Keyup?

Both are used as per the need of your program and as per the convenience of the user. keyup Fires when the user releases a key, after the default action of that key has been performed. keydown Fires when the user depresses a key.

How do I stop Keydown event?

To cancel keydown with JavaScript, we can call preventDefault in the keydown event handler. For instance, we write: document. onkeydown = (evt) => { const cancelKeypress = /^(13|32|37|38|39|40)$/.

What is the event for Onkeydown?

The onkeydown event occurs when the user is pressing a key (on the keyboard).


1 Answers

This should only fire the event once, so if it is firing twice I would check a couple of things.

Check that you aren't handling the key down event on a parent control. This could be a panel or the containing window. Events will bubble down through the visual tree. For example a key down on a textbox will also be a keydown on the window containing the textbox.

To stop this happening you can mark the event as handled as below;

e.Handled = true;

The other thing to check is that you aren't subscribing to the event twice. The XAML will do the same as;

TextBoxUser.KeyDown += TextBox_KeyDown

so check that you don't have this in your code behind.

You can check the sender and e.OriginalSource property to see where the event is being fired from.

like image 98
daniellepelley Avatar answered Sep 21 '22 13:09

daniellepelley