11

I have question about the KeyEventArgs's KeyCode and KeyData and KeyValue. KeyCode and Keydata are Keys type, but I don't know what the difference between them is. For KeyValue, I don't know what it is -- it has an int type, does it return the char value of the pressed key?

I don't have much experience with Key events; any explanation of how they function and how to use them would be greatly appreciated.

MPelletier
  • 16,256
  • 15
  • 86
  • 137
Bosak
  • 2,103
  • 4
  • 24
  • 43

1 Answers1

19

KeyCode contains data for the key that produced the KeyUp or KeyDown event. KeyData contains the combination of that key together with CTRL, SHIFT or ALT if any of those were pressed.

Example:

  • Press (and hold) CTRL. KeyDown will be raised, KeyCode will be Keys.ControlKey, KeyData will be Keys.ControlKey | Keys.Control.
  • While still holding CTRL pressed, press SHIFT. KeyDown will be raised, KeyCode will be Keys.ShiftKey and KeyData will be Keys.ShifKey | Keys.Shift | Keys.Control.

Note that KeyData and KeyCode can contain any value in the Keys enumeration (such as Keys.A, Keys.NumPad4 or Keys.Up). Note that when one of the modifier keys are pressed, it is represented by two values in KeyData (one for they key and one for the modifier value). The modifiers are also available through the Modifiers property.

KeyValue will return a numerical value representing the key, essentially an integer representing the value found in KeyCode.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
  • So key data can only be CTRL ALT or SHIFT keys?And what about KeyValue? – Bosak Aug 16 '11 at 12:30
  • So when i press ahift KeyCode can only be Keys.ShiftKey and it will never be Keys.Shif? Oh and is Keys enumerated from 0 to MaxKeys or is it enumerated like in the ASCI table for example A - 65 – Bosak Aug 16 '11 at 12:45
  • 1
    @Bosak: exactly. Note though that pressing 'A' will always give 65, regardless of whether you are typing an uppercase or lowercase letter. Remember that the values represent the keys, not the letters they produce. – Fredrik Mörk Aug 16 '11 at 12:59
  • Yes if i need to check the letters ill need to check the modiffers or key data for a shift key :) Thanks alot you helped me! – Bosak Aug 16 '11 at 13:01