Friday, February 26, 2010

How to detect CTRL + ALT key combinations in WPF


Key combinations are a fancy pair of words to describe pressing/holding multiple keyboard buttons to perform a command.

Ex:- Few of ever using key combinations are,
  • Ctrl + S to Save,
  • Ctrl + C to Copy,
  • Alt + F4 to close an application,
  • Ctrl + Alt + Del to lock our computer, etc.,  
There are many such combinations, and while I provided some common ones, many applications like Visual Studio provide their own key combinations to help save you some time. Let's add some key combinations to our little program also.

    void SpecialKeyHandler(object sender, KeyEventArgs e)
    {
        // Ctrl + N
        if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.N))
        {
            MessageBox.Show("New");
        }

        // Ctrl + O
        if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.O))
        {
            MessageBox.Show("Open");
        }

        // Ctrl + S
        if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.S))
        {
            MessageBox.Show("Save");
        }

        // Ctrl + Alt + I
        if ((Keyboard.Modifiers == (ModifierKeys.Alt | ModifierKeys.Control)) && (e.Key == Key.I))
        {
            MessageBox.Show("Ctrl + Alt + I");
        }
    }

The key approach doesn't work for another reason because your commonly used Alt, Ctrl, Shift, and Windows keys can't be accessed from the Key enum at all. Instead, those four keys can only be accessed using the ModifierKeys enum and checking whether Keyboard.Modifiers is equal to that key.