A. Wolf A. Wolf - 1 year ago 132
C# Question

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 & Modifiers.Shift) == Modifiers.Shift)
if ( Key.Shift != e.Key && Key.LeftAlt != 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
clause). The second
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
Catch when a key is released:

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


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?
There's a way to handle shortcuts in a better way? Thank you.

Answer Source

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;

            return e.Key;

You could check my answer here for more info.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download