Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Char from Key

I am coding a custom text editor, and I use KeyDown and KeyUp events. That events gets a KeyEventArgs from parameters where a "Key" instance is included.

How I can transform that "Key" to a real char?

Using Key.ToString() with a "." I get a "OmePeriod" or with "," I get a "OmeComma". I can transform that values directly...but It is a hard work, and I am sure that must exist any class that transform that Keys to the real "char".

Thanks!

Regards.

like image 641
Jesús Galindo Avatar asked Sep 06 '11 08:09

Jesús Galindo


3 Answers

The main problem here is that the event you are catching is reel keyboard event and that the key is indeed a key and NOT a character. In between is the keymap ! For example, when typing shift-A, you will receive two event instead of one for keypressed.

this discussion can help : C# How to translate virtual keycode to char?

like image 64
VdesmedT Avatar answered Nov 16 '22 09:11

VdesmedT


Instead of using the KeyDown event, try using the TextInput event. Attach an event handler that looks like this:

private void Grid_TextInput(object sender, TextCompositionEventArgs e)
{
    Char keyChar = (Char)System.Text.Encoding.ASCII.GetBytes(e.Text)[0];
    Debug.WriteLine(keyChar);
}

Note, this grabs only the first byte, and this will not work for international (Unicode) text. It may not work for more complex text input events either, so be advised!

See this MSDN article for some more info.

like image 35
markmuetz Avatar answered Nov 16 '22 09:11

markmuetz


This gives you exactly what you need .... that too locale specific character from the Keyboard's Key code ...

how to capture the '#' character on different locale keyboards in WPF/C#?

like image 3
WPF-it Avatar answered Nov 16 '22 08:11

WPF-it