In WPF, I want a textbox to throw an event for any and every key press while that textbox is focused. I'm not sure of the full extent of what keys aren't triggering the KeyDown
event, but as an example, I know that if I press the left or right arrow, then it doesn't trigger the event, the cursor just moves left or right respectively. My end all goal is to get the System.Windows.Forms.Keys
enum value for any key that was pressed. I already found this question about converting between Key
and Keys
and now I just need to intercept any and every key. Is there a different event I can respond to like PreviewKeyDown
(I'll be honest, I don't know the difference between the normal event and the "previewed" event) or is there a property on the textbox sort of like AcceptsTab
?
Asked
Active
Viewed 2,525 times
3

Community
- 1
- 1

Corey Ogburn
- 24,072
- 31
- 113
- 188
-
Difference between KeyDown and PreviewKeyDown: http://www.dotnetspider.com/forum/130497-what-event-bubbling-event-tunneling.aspx – Bas Jul 28 '11 at 15:01
-
Preview events are raised before the action.. for example if you pressed "A" key, preview event will be raised before that "A" appears in the text area and key down event will be raised after "A" appears in the text area. – Bathineni Jul 28 '11 at 15:16
1 Answers
5
The PreviewKeyDown-Event is what you need. It is fired before the TextBox has processed key messages and therefore you get an event for all keys.
If you consume a key in the PreviewKeyDownEvent, you can set the Event.Handled-property to true, and the TextBox will take no more notice from the key.
You will find the "Preview"-prefix for many events. It is a pattern that is used often. Look here for more information. The interesting part is the "Routing Strategies" section.

HCL
- 36,053
- 27
- 163
- 213