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?

4
  • 1
    Look at the statement. Can KeyCode every be equal to two different values at once? Jun 3, 2013 at 21:28
  • Replace e.KeyCode == whatever with e.KeyCode & whatever == whatever Jun 3, 2013 at 21:28
  • There is a very similar post on SO here
    – Evan L
    Jun 3, 2013 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. Jul 15, 2013 at 21:23

1 Answer 1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.