Svish
Svish

Reputation: 158351

C#: In a KeyDown event, what should I use to check what key is down?

In a KeyDown event, I have the KeyEventArgs to work with. It has (among other things) these three properties:

Which one should I use for what?

Upvotes: 5

Views: 21597

Answers (4)

Richard Szalay
Richard Szalay

Reputation: 84824

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.

Upvotes: 12

Treb
Treb

Reputation: 20299

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.

Upvotes: 0

Soltys
Soltys

Reputation: 41

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

Upvotes: 0

Cerebrus
Cerebrus

Reputation: 25775

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.

Upvotes: 1

Related Questions