In a KeyDown event, I have the KeyEventArgs to work with. It has (among other things) these three properties:
e.KeyCode
e.KeyData
e.KeyValue
Which one should I use for what?
In a KeyDown event, I have the KeyEventArgs to work with. It has (among other things) these three properties:
e.KeyCode
e.KeyData
e.KeyValue
Which one should I use for what?
Edit: Somehow I misread your question to include checking a valid character. Did you modify it? I've added a description of each.
If you just need the character, I'd probably recommend using the KeyPress event and using the KeyPressEventArgs.KeyChar property. You can then use Char.IsLetterOrDigit() to find out if it's a valid character.
Alternatively, you might be able to cast KeyEventArgs.KeyCode to a char and then use Char.IsLetterOrDigit on that.
I would suggest using the KeyCode
property to check against the Keys
enumeration for most operations. However some of the basic differences below might help you to better decide which one you need for your situation.
Differences:
KeyCode
- Represents the Keys
enumeration value that represents the key that is currently in Down state.
KeyData
- Same as KeyCode
, except that it has additional information in the form of modifiers - Shift/Ctrl/Alt etc.
KeyValue
- The numeric value of the KeyCode
.
Very basic using of KeyDown
private void tbSomeText_KeyDown (object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.B && e.Modifiers != Keys.Shift) {
MessageBox.Show("You Pressed b");
}
else if (e.KeyCode == Keys.A && e.Modifiers == Keys.Shift) {
MessageBox.Show("You Pressed Shift+A");
}
}
See my answer to your other question:
Use the KeyPressed event.
Quoting MSDN:
A KeyPressEventArgs specifies the character that is composed when the user presses a key. For example, when the user presses SHIFT + K, the KeyChar property returns an uppercase K.
This way you don't need to mess around with e.KeyCode
,
e.KeyData
and
e.KeyValue
.