Monday 21 November 2011

How to Convert a System.Windows.Input.Key to a Char

Today i wanted to write a custom input control that hooks up to the KeyDown event of a CustomControl to collect the typed chars. In the KeyEventArgs you find a e.Key that is of type System.Windows.Input.Key. I tried to use the KeyConverter or cast it to a char or string, but nothing seems to work.
 
private string _text = string.Empty;
 
void MyControl_KeyDown(object sender, KeyEventArgs e)
{
  _text += e.Key;
}
 
 
The solution is to hook to another event called TextInput. The provided TextCompositionEventArgs has a Text property that is excatly what we want. The event handler will look like this:
 
void MyControl_TextInput(object sender, TextCompositionEventArgs e)
{
    _input += e.Text;
}
 
 

1 comment: