How should we handle keyboard events in WPF? Should it be KeyUp or KeyDown?
Asked Answered
B

2

5

I have been using WPF with all the tunneling and bubbling events and I must say they are simply great and powerful.
But what I always question myself is whether to use the [PreviewKeyUp and KeyUp] or [PreviewKeyDown and Keydown]?

Which combination should I be using to react to key presses and why?

Beautify answered 2/2, 2012 at 17:10 Comment(1)
It depends on where you want to be in chain. KeyDowns get processed before KeyUps. So if you want to stop it before it gets to an event handle the KeyDown. Look for Event Bubbling and Routed Events on MSDN.Belgae
I
8

Depends on what you want to do:

  1. PreviewKeyDown = BEFORE the key is pressed
    Example: If you have the event on a textbox the current key pressed is not added to the TextBox.Text
  2. PreviewKeyUp = BEFORE the key is let go
  3. KeyDown = AFTER the key is pressed
    Example: If you have the event on a textbox the current key pressed is added to the TextBox.Text
  4. KeyUp = AFTER the key is let go

So again it depends on what you want to do. If you want to add TextBox validation use PreviewKeyDown to ignore the text if its incorrect.

If you want to do something when the user let go of SPACE then us KeyUp

Ignatzia answered 2/2, 2012 at 17:30 Comment(0)
L
0

It all depends upon the situation, for example, selecting an item in a list will want to be KeyDown so that the key can be held and the selected item changed.

If you have an element with multiple visual states, e.g. a button, the KeyDown may change the visual state, then the KeyUp will return the visual to the original state and execute the command.

In your situation it will all depend upon when you want the event to be raised, I wouldn't say either one was better than the other as they are for different uses.

Lidda answered 2/2, 2012 at 17:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.