Home  separator  Input  separator  Keyboard
Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  


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;
}
 
 




Last modified: 2009-06-17 17:31:13
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
nandy
Commented on 6.May 2009
is it really working ?
Vimal
Commented on 19.May 2009
Can you explain it a bit more?
KingMarcusVi...
Commented on 27.May 2009
Can WPF application windows can process mouse events through SendMessage() notifications (with or without mouse pointer hovering above its window)?
George
Commented on 18.June 2009
First example is NOT WORK.
sara
Commented on 26.June 2009
I tried its not working.
Christian Moser
Commented on 26.June 2009
Hi, what exactly is not working?
Did you register the eventhandler? TextInput += MyControl_TextInput;
Do you receive the entered text in the _text string?
Mr Sda
Commented on 11.August 2009
Heres some keyboard input for you buddy.
Your a boss eyed jack ass.
Agree
Commented on 6.September 2009
Agree with Mr.Sda
tarahgiv
Commented on 17.December 2009
Oh, good joke) Why do birds fly south for the winter? It's quicker than driving.
___________________________
<a href= http://ordervigerausa.fizwig.com/site_map.html >cealis order San Jose</a>
Jonathan
Commented on 7.January 2010
This does not work !!
Phil
Commented on 28.January 2010
TextBox will mark the key press as handled, use PreviewTextInput event.
ajay sharma
Commented on 2.March 2010
Code is not working....
COPYRIGHT
Commented on 23.August 2010
2 things:

1. you paki's are dumb as hell

2.COPYRIGHT INFRINGEMENT AT ITS FINEST!!!!!!!!!

MOSER IS GREASY AS HELL
Christian
Commented on 23.August 2010
Its funny that you guys find my articles so helpful considering I just copy and pasted random shit from other random sites that I found. Its all good though because those google ads are making me cash!!!
Christian M
Commented on 23.August 2010
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this from another website

Name
E-Mail (optional)
Comment