Search code examples
wpfkeydownctrl

Detecting of keydown combination Ctrl+= (Ctrl+Key.OemPlus)


I have a RichTextBox control and I need to handle CTRL + = keydown combination. = sign itself is Key.OemPlus. So the problem is that when I press this combination, the KeyDown event is not raised.

I tried different code variants, with Keyboard.IsKeyDown for both pressed keys, with Keyboard.Modifiers for CTRL key, etc...

if (Keyboard.IsKeyDown(Key.OemPlus) && Keyboard.IsKeyDown(Key.LeftCtrl))
{
     // do smth
}
if (Keyboard.IsKeyDown(Key.OemPlus) && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
     // do smth
}
if (args.Key == Key.OemPlus && Keyboard.IsKeyDown(Key.LeftCtrl))
{
     // do smth
}
if (args.Key == Key.OemPlus && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
     // do smth
}

So, none of the above code attempts worked and I can't find the answer in Google. How to solve this problem?


Solution

  • Classic WPF routed event problem. The KeyDown routed event is being handled by the RichTextBox internally. It thinks Ctrl + = is a command that it recognized, so it eats the KeyDown event before it gets to you. Luckily there is a solution: PreviewKeyDown. If you change your code to handle PreviewKeyDown instead of KeyDown you should find that the events fire as you expect.