#1,076 – Two Ways to Check for Use of Modifier Keys in Keypress Handlers

You can check for the presence of modifier keys (e.g. Alt, Ctrl, Shift, or Windows key) in keypress handlers using the KeyboardDevice.Modifier property.  For example:

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Key == Key.G) &&
                (e.KeyboardDevice.Modifiers == ModifierKeys.Control))
                MessageBox.Show("Ctrl+G detected");
        }

Note that this method doesn’t distinguish between whether you pressed the left vs. right Ctrl keys.  This is normally what you want.  If you do want to distinguish between the two, you can explicitly check for left vs. right.

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Key == Key.G) &&
                (Keyboard.IsKeyDown(Key.LeftCtrl)))
                MessageBox.Show("Left Ctrl+G detected");
            else if ((e.Key == Key.G) &&
                (Keyboard.IsKeyDown(Key.RightCtrl)))
                MessageBox.Show("Right Ctrl+G detected");
        }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,076 – Two Ways to Check for Use of Modifier Keys in Keypress Handlers

  1. Pingback: Dew Drop – May 20, 2014 (#1780) | Morning Dew

  2. Pingback: #1,077 – Checking for Single Modifer vs. Multiple Modifier Keys | 2,000 Things You Should Know About WPF

Leave a comment