问题
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?
回答1:
Edit: Somehow I misread your question to include checking a valid character. Did you modify it? I've added a description of each.
- KeyCode is the Keys enumeration value for the key that is down
- KeyData is the same as KeyCode, but combined with any SHIFT/CTRL/ALT keys
- KeyValue is simply an integer representation of KeyCode
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.
回答2:
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 theKeys
enumeration value that represents the key that is currently in Down state.KeyData
- Same asKeyCode
, except that it has additional information in the form of modifiers - Shift/Ctrl/Alt etc.KeyValue
- The numeric value of theKeyCode
.
回答3:
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");
}
}
回答4:
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
.
来源:https://stackoverflow.com/questions/564338/c-in-a-keydown-event-what-should-i-use-to-check-what-key-is-down