How do I get the normal characters from a WPF KeyDown event? How do I get the normal characters from a WPF KeyDown event? wpf wpf

How do I get the normal characters from a WPF KeyDown event?


Can you use the TextInput event rather than KeyDown? the TextCompositionEventArgs class allows you to directly retrieve the text entered via the e.text property

private void UserControl_TextInput(    object sender,     System.Windows.Input.TextCompositionEventArgs e){     var t = e.Text;}


Unfortunately there's no easy way to do this. There's 2 workarounds, but they both fall down under certain conditions.

The first one is to convert it to a string:

TestLabel.Content = e.Key.ToString();

This will give you the things like CapsLock and Shift etc, but, in the case of the alphanumeric keys, it won't be able to tell you the state of shift etc. at the time, so you'll have to figure that out yourself.

The second alternative is to use the TextInput event instead, where e.Text will contain the actual text entered. This will give you the correct character for alphanumeric keys, but it won't give you control characters.


From your concise question, I'm assuming you need a way to get the ASCII value for the pressed key. This should work

private void txtAttrName_KeyDown(object sender, KeyEventArgs e)        {            Console.WriteLine(e.Key.ToString());            char parsedCharacter = ' ';            if (Char.TryParse(e.Key.ToString(), out parsedCharacter))            {                Console.WriteLine((int) parsedCharacter);            }        }

e.g. if you press Ctrl + S, you'd see the following output.

LeftCtrlS83