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

巧了我就是萌 提交于 2020-01-03 13:07:11

问题


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 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.




回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!