Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the exact difference between Keys.Control/Shift and Keys.ControlKey/ShiftKey? [duplicate]

What's the exact difference between Keys.Control and Keys.ControlKey/Keys.Shift and Keys.ShiftKey in System.Windows.Forms?

I've googled it but nothing specific came up, and it doesn't seem to be documented on MSDN either.

Personally, I always use Keys.Control/Keys.Shift, because it works fine.


Edit: After reading KreepN's answer, I thought if you never have to use Control/Shift, why are they in the framework?

I mean, they aren't even the physical keys, so I can't see the reason why Microsoft decided to create them.

Are there circumstances where it's better to use Control/Shift?

like image 813
lesderid Avatar asked Sep 21 '11 15:09

lesderid


1 Answers

ControlKey and ShiftKey (and Menu--which you would assume would have been named AltKey) represent the physical keys themselves. In other words, they are "actual" keys and can be found in the KeyCode property of a KeyEventArgs object.

Control, Shift, and Alt, on the other hand, will never appear in the KeyCode property, but their values can be found in the KeyData property. It seems you never actually NEED to use these constants, because the framework already pulls them out for you via the Alt, Control, and Shift properties of the KeyEventArgs object, but you CAN use them to test against the KeyData property if you really want to.

Source with Examples.

Edit for your edit:

Look at the values that are returned when the "a" key is pressed:

a (unshifted) / 41 / 41

A (Shift+a) / 41 / 10041

Ctrl+a / 41 / 20041

The "KeyCode" in this case is = 41 for all modifiers. You could use this in code if all you cared about was the primary button pressed, in this case "a".

If you wanted to have different functionality based on if a modifier was pressed you would need to get more specific and reference the "KeyData" field and look for the # that denoted a certain modifier. In this case "100" for shift and "200" for control at the beginning of the field.

That's not to say you couldn't just check for the "41" at the end of the KeyData field, but I've never been one to complain about convenience.

It would be safe to say that the "difference" you are looking for between them in your first question is that they reference different property fields.

Edit for additional relevance: The key modifier values combined with the key value directly correlate to the Shortcut enumeration members. For example: Shortcut.CtrlF8 ( 0x20077 ) is the same as Keys.Control | Keys.F8 ( 0x20000 | 0x77 )

This can be useful when dealing with the defined Shortcut properties of menu items.

like image 61
KreepN Avatar answered Sep 22 '22 23:09

KreepN