1
votes

I have a Window in WPF with a KeyDown event handler attached.

When the user presses a numeric key (0-9) I respond to the event. I use the 0-9 as shortcut keys to select a radiobutton. Eg. pressing key 3 will select the 3'rd radiobutton.

The problem is that when the user presses a numeric key inside a TextBox I don't want to handle the keypress as a shortcut, because I want to keep the default implementation of the TextBox.

Right now when the user presses 3 when inside a TextBox, the text of the TextBox is set to 3, but also the 3'rd radiobutton is selected.

I thought the TextBox would set e.Handled to true when the user presses the key down inside the TextBox, but that isn't the case.

Also the TextBox is just an example. If the user enters something in other input controls in my hierarchy I don't want to respond to KeyDown events.

I guess I need a better understanding of routed events to solve this, or maybe solve this in another way?

2
Sounds like you are planning to give your users a headace. The application needs to be user friendly - this is just as important as the underlying code working. I fear user confusion. Would it be better to map F-buttons instead of numerics? (I realize you may have your reasons, just asking)Tedd Hansen
I couldn't agree more myself. But the users are used to these shortcuts from an earlier piece of software so it's a requirementBen Anderson

2 Answers

0
votes

You can check the OriginalSource property of RoutedEventArgs (KeyPressEventArgs in your case). If it is TextBox, don't handle it. If it is not, do your RadioButton selection logic.

0
votes

Try using the Form.KeyPreview property and also use the ActiveControl property to trigger the logic