Reputation: 24717
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
?
Upvotes: 3
Views: 2546
Reputation: 36765
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.
Upvotes: 5