How to stop WPF KeyDown events from bubbles from certain contained controls (e.g. TextBox)?

My program is quite large and uses WPF, and I want to have a global shortcut that uses "R", without modifiers.
There are many controls, such as TextBox, ListBox, ComboBox, etc., which use letters inside the control itself, which is fine - this is right for me.
But - I want this KeyDown event to go to the main window , where it would trigger a shortcut at any time when the user enters the letter "R" in the TextBox, for example.
Ideally, I would like to be able to do this without having to specify (and do if-then logic) each instance / type of control that could receive ordinary alphanumeric keystrokes (and not just TextBox controls, although they are the worst offenders).

+8
c # event-bubbling wpf
source share
2 answers

Just check that OriginalSource is in your KeyDown handler in the window:

 private void Window_KeyDown(object sender, KeyEventArgs e) { if(e.OriginalSource is TextBox || e.OriginalSource is DateTimePicker) //etc { e.Handled = true; return; } } 

Or, if you use InputBindings, experiment with setting e.Handled = true in the KeyDown or PreviewKeyDown in your window, and not in individual controls. Anyway, I think OriginalSource is the key to your answer. (I swear it was not a pun).

+6
source share

There is an event when you are handling the KeyDown , and it should pass you KeyEventArgs . From there, you can set Handled to true so that it does not bubble.

Example

 private void TextBoxEx_KeyAction(object sender, KeyEventArgs e) { e.Handled = true; } 
0
source share

All Articles