#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 !");
        }
Advertisements

#626 – Key Up/Down Sequence When Using CTRL Key

When you use the Ctrl-key in combination with another key, e.g. pressing Ctrl-G, the control that has focus will receive KeyUp and KeyDown events for both the Ctrl key and the main key that you are pressing.

For example, if a TextBox control has focus and I press Ctrl-G (which doesn’t normally do anything in a TextBox) and I use the Ctrl key on the left side of the keyboard, I’ll see the following events for the TextBox, in the sequence listed.

  • PreviewKeyDown, key = LeftCtrl
  • KeyDown, key = LeftCtrl
  • PreviewKeyDown, key = G
  • KeyDown, key = G
  • PreviewKeyUp, key = G
  • KeyUp, key = G
  • PreviewKeyUp, key = LeftCtrl
  • KeyUp, key = LeftCtrl

In this case, you can see that my sequence in pressing/releasing the keys was:

  • Press and hold left Ctrl key
  • Press G key
  • Release G key
  • Release Ctrl key