When handling Control.OnKeyPress
event, there is a KeyPressEventArgs
that contains a KeyChar
.
For usability reasons I need exactly the same KeyChar
but when handling OnKeyDown
event.
The KeyEventArgs
does not contains any char related data. I mean, if press the A
key with or without Shift
its not affecting the KeyCode
, KeyData
or KeyValue
. The same when using another language, i still getting capital english values.
How to get a KeyPressEventArgs.KeyChar
inside KeyDown
event?
Thanks.
The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
Occurs when a key is pressed while the control has focus.
Both are used as per the need of your program and as per the convenience of the user. keyup Fires when the user releases a key, after the default action of that key has been performed. keydown Fires when the user depresses a key.
Convert it. Here is simple function for converting 'A' to 'a'. It converts only capital chars from [A-Z] set. The value 32 is diff between 'A' and 'a'.. Sure you can extend it to your requirements, or ask for feature here.
char getChar( KeyEventArgs e )
{
int keyValue = e.KeyValue;
if ( !e.Shift && keyValue >= (int) Keys.A && keyValue <= (int) Keys.Z )
return (char)(keyValue + 32);
return (char) keyValue;
}
if you need it to works with your current culture you should override ProcessKeyMessage Control method:
protected override bool ProcessKeyMessage( ref Message m )
{
if ( ( m.Msg == 0x102 ) || ( m.Msg == 0x106 ) ) // this is special - don't remove
{
char c = (char) m.WParam; // here is your char for OnKeyDown event ;)
}
return base.ProcessKeyMessage( ref m );
}
Hope it helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With