Question

We have a WPF application where we need to detect if the user is typing something that can appear in a textbox. WinForms used to have a nice OnKeyPressed override that differed from OnKeyDown in that it was only called when a printable character was typed (e.g. it differentiated between 'A' and 'a' but not between the '1' on the top row vs. the numeric keypad. It also ignored keys like 'Shift', etc.) We need to duplicate that functionality in WPF.

Now I know I can override OnKeyDown and inspect the keycode, but that means manually testing for every possible key that would result in something appearing in a textbox. That seems to be the consensus from the other similar SO questions that I've found, but I just can't believe something so basic would be left out of the API.

Asides from a monster if-tree, one 'hacky' solution is to use an in-memory textbox, pass the keycode to it, then inspect if the text has a length. But I'm getting nauseous even typing that as a possible solution! UGH!! I feel dirty!

SO... what's the easiest way to tell if a user pressed a key or keys that will result in a printable character?

TIA,

Mark

Was it helpful?

Solution

Actually, I think I just found it so I'm posting the answers for others. You don't use any 'Key' events at all. WPF more clearly separates those out from the textual values. As such, you override the OnPreviewTextInput and/or OnTextInput functions. To get what was actually typed, check the .Text property on the event args which returns a simple string.

Done and done!

Hope this helps others! Been driving me up a wall!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top