Search code examples
c#wpfshortcut

Catch Alt + other key shortcut


I have to catch user's input to send a shortcut to my WPF application.
I found on internet that I have to do something like this:
Catch when a key is pressed:

void keyDown(object sender, KeyEventArgs e)
{
    if (Keyboard.Modifiers.HasFlag(Modifiers.Shift))
        KeyPressed.SetShift(true);
    if (Key.Shift != e.Key && Key.LeftAlt != e.Key && ....) 
        KeyPressed.SetKey(e.Key);
}

where KeyPressed is a class with static boolean variables to catch if ⇧Shift, Alt or Ctrl and another key are pressed (with Alt and Ctrl instead of ⇧Shift in the if clause). The second if is to catch a key different from Alt, ⇧Shift, Control for the shortcut. For example, for the shortcut Alt+C we have:

  1. KeyPressed.Shift = false;
  2. KeyPressed.Alt = true;
  3. KeyPressed.Ctrl = false;
  4. KeyPressed.key = Key;

Where the last element is of type System.Window.Input.Key.
Catch when a key is released:

void keyUp(object sender, KeyEventArgs e)
{ 
    if (KeyPressed.getShift()) 
        this.textField.Text += "+Shift";
    if (KeyPressed.getKeyCode())
        this.textField.Text += "+" + KeyPressed.k.toString();

    KeyPressed.SetShift(false);
}

and here simply I append to a textField the input received, after that I set all keys to false to catch the next shortcut correctly.

This code works fine for all shortcuts like Ctrl+A, Ctrl+Alt+C, ⇧Shift+L, Alt, but when I press the shortcut like Alt+V, it catchs only Alt, not the other key.

How can I manage this? Is there a way to handle shortcuts in a better manner?


Solution

  • You need to get the actual key when in case of a SystemKey (Alt etc), you can use this helper function to get the real key behind the system key.

    public static Key RealKey(this KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.System:
                return e.SystemKey;
    
            case Key.ImeProcessed:
                return e.ImeProcessedKey;
    
            case Key.DeadCharProcessed:
                return e.DeadCharProcessedKey;
    
            default:
                return e.Key;
        }
    }
    

    You could check my answer here for more info.