Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Thursday, July 19, 2012

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:

  1. Try this with the backspace key. Doesn't work for multiple backspaces. Looks like e.Text = '\b'.

    ReplyDelete