简体   繁体   中英

How to not handle a KeyDown Routed Event that has already been handled by eg. a TextBox

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM