0

My program has several key combinations, but whenever Shift, Alt or Control is pressed, they override any other keys that are not one of those 3, even though they don't override each other. Can someone please help me find a way to make sure the KeyEventArgs (or some equivalent function) gets both, like for example Shift + W? In the code below, I only every get the shift writeline, never the combo, regardless if I started by holding down the W or the Shift.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Shift)
    {
        if (e.KeyData == Keys.W || e.KeyData == Keys.S)
        {
            Console.WriteLine("combination");
        }
        Console.WriteLine("shift");
     }
}
Daniel
  • 175
  • 2
  • 2
  • 8

1 Answers1

1

The KeyData property exposes the key that was pressed as well as the modifiers that are active. So you'd use it like this:

private void Form1_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyData == (Keys.Shift | Keys.W) || e.KeyData == (Keys.Shift | Keys.S)) {
        Console.WriteLine("combination");
    }
 }

You can do it your way as well, but then you have to use a different property, KeyCode. It exposes only the key code without the modifier keys:

private void Form1_KeyDown(object sender, KeyEventArgs e) {
    if (e.Shift) {
        Console.WriteLine("shift");
        if (e.KeyCode == Keys.W || e.KeyCode == Keys.S) {
            Console.WriteLine("combination");
        }
    }
 }

Which one you'd use is entirely up to you. Do however keep in mind that using the form's KeyDown event is not very correct. It also requires setting the KeyPreview property to true. That's a pretty ugly VB6 compatibility property, you cannot see every possible keystroke. The navigation keys are filtered, like it was done in VB6. The native Winforms way is to override the ProcessCmdKey() method instead. Which does require you to work with KeyData.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • thanks a million. I FINALLY got a key combination. Can you please expand a little on the "overriding ProcessCmdKey() method"? I know how the initial code goes ___ `protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { /*whatever logic is wanted here*/}` but I thought a Keys argument could only handle 1 key? – Daniel Sep 06 '14 at 02:31
  • Sure, that is not different from KeyDown. – Hans Passant Sep 06 '14 at 02:32
  • Wait, so Keys keyData could contain multiple keys? – Daniel Sep 06 '14 at 02:34
  • It contains the KeyCode and the *modifier keys* that might be down. So any combination that involves Alt, Shift or Ctrl are not a problem. But you already knew that. – Hans Passant Sep 06 '14 at 02:45
  • how would I access the the modifier keys in the `ProcessCmdKey()`? – Daniel Sep 06 '14 at 02:51
  • I showed you, first snippet. You already knew that too, hard to figure out why you are asking these questions. Good luck with it. – Hans Passant Sep 06 '14 at 02:56