#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 .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: