17 December 2015

Pressing ctrl+key in a WPF Window Application

We had a bug on a WPF application where KeyUp="MainControl_KeyUp" had been used for detecting ctrl+B

if (e.Key == Key.B && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)

This meant that only the B + right control would trigger the event.
Changing the event to being a KeyDown event and this post help solve the issue so both control keys now can be used to detect the key combination in the event context.


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


http://wpf.2000things.com/2012/08/17/627-detecting-whether-the-ctrl-key-is-pressed-in-a-keydown-event-handler/
http://wpf.2000things.com/tag/keydown/

No comments: