#627 – Detecting Whether The Ctrl Key Is Pressed In a KeyDown Event Handler

When you press a Ctrl-key combination (e.g. Ctrl+G) and you are monitoring KeyDown (or KeyUp) events, you’ll see two separate KeyDown events–one for the Ctrl key and one for the key pressed with it.

If you want to respond to a Ctrl-key combination within a KeyDown event handler, you can do the following :

  • Use the KeyEventArgs.Key property to see whether the event is being fired because the combination key (e.g. ‘G’) is being pressed
  • Use the Keyboard.IsKeyDown method to check whether the Ctrl key is also currently down
        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Key == Key.G) &&
                (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
                MessageBox.Show("You pressed Ctrl+G !");
        }

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.

One Response to #627 – Detecting Whether The Ctrl Key Is Pressed In a KeyDown Event Handler

  1. Pingback: #1,076 – Two Ways to Check for Use of Modifier Keys in Keypress Handlers | 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: