0

I want my application to respond to Ctrl + M it will do something:

if (e.KeyCode == System.Windows.Forms.Keys.M 
    && e.KeyCode == System.Windows.Forms.Keys.RControlKey)

I tried to click Ctrl + M (I tried both left and right Ctrl keys) and it stops at a breakpoint on the if but never goes in. Why not?

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
Revuen Ben Dror
  • 237
  • 7
  • 17
  • 1
    Look at the statement. Can `KeyCode` every be equal to two different values at once? – Jesus Ramos Jun 03 '13 at 21:28
  • Replace e.KeyCode == whatever with e.KeyCode & whatever == whatever – It'sNotALie. Jun 03 '13 at 21:28
  • There is a very similar post on SO [here](http://stackoverflow.com/questions/1265634/keydown-recognizing-multiple-keys) – Evan L Jun 03 '13 at 21:33
  • `Ctrl+M` has `ASCII` code decimal `13` (= code of `M` minus 64). You get the same code for "Carriage Return" or `Enter`. Enums `System.Windows.Forms.Keys.Enter` and `System.Windows.Forms.Keys.Return` both have value `13`. – Axel Kemper Jul 15 '13 at 21:23

1 Answers1

11

What you're doing doesn't make sense:

e.KeyCode is an enum value, which can only hold one value at a time, an enum value cannot be both Keys.M and Keys.RControl at the same time(1).

Windows handles Control (and other special keys) as modifiers, the correct way is like so:

if(e.KeyCode == Keys.M && e.Control) {

or

if(e.Keycode == Keys.M && (e.Modifiers & Keys.RControl) == Keys.RControl) {

(1)(not counting Flags, and I know Keys is marked as Flags, but i'm trying to keep things simple)

Dai
  • 141,631
  • 28
  • 261
  • 374