简体   繁体   中英

Textbox keydown for any key press?

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM