2

So I'm making an application that will use a lot of keys on the keyboard, and I want to put them all in a switch-case. My problem is, the application also needs to detect key combinations like Shift + 9 for brackets, etc. I tried this:

case Keys.Shift & Keys.D9:

But I found out that the '&' operator is unary or binary, and no other operators seem to work.

Can I solve this by making a nested switch-case like:

case Keys.Shift:
    switch (e.KeyCode)
    {
         case Keys.D9:

         break;
    }
    break;

Or is this bad practise? Because I don't really want to make a big list of if-else statements.

Thanks in advance.

TCDutchman
  • 41
  • 11

1 Answers1

1

I wouldn't nest switch-case but use if-statements.

Also, to check for key combinations I would suggest you use something like this:

if ((ModifierKeys & Keys.Shift) == Keys.Shift)
{
    switch (e.KeyCode)
    {
        case Keys.D9:
            //do stuff
            break;
    }
}
Oceans
  • 3,445
  • 2
  • 17
  • 38
  • So basically, If I understand correctly, I would need a switch-case for when the user presses Shift and one for when the user doesn't press Shift? – TCDutchman Mar 18 '16 at 15:55
  • `ModifierKeys` indicates which of the modifier keys is in a pressed state. The if-statement in my example checks if this is the shift-key. So I would nest a couple of if statements for the relevant modifier keys (alt, shift, control) and in the final `else` you can have your regular switch-case for when only 1 key is pressed. – Oceans Mar 18 '16 at 16:00