Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want the ASCII characters passed by the e.Key property from a WPF KeyDown event.

like image 381
Malcolm Avatar asked Jan 28 '09 08:01

Malcolm


3 Answers

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;
}
like image 97
Thomas AUGUEY Avatar answered Oct 14 '22 20:10

Thomas AUGUEY


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.

like image 30
Steven Robbins Avatar answered Oct 14 '22 19:10

Steven Robbins


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.

LeftCtrl
S
83
like image 3
Gishu Avatar answered Oct 14 '22 19:10

Gishu