How do I stop WPF KeyDown events from bubbling up from certain contained controls (such as TextBox)?

我的梦境 提交于 2019-12-21 09:22:09

问题


My program is quite large, and uses WPF, and I want to have a global shortcut key that uses 'R', with no modifiers.
There are many controls such as TextBox, ListBox, ComboBox, etc. that all use letters inside the control itself, which is fine - that's correct for me.
But - I want to keep that KeyDown event from bubbling up to the main window, where it would trigger the shortcut any time a user is typing the letter 'R' in a TextBox, for example.
Ideally, I would like to be able to do this without having to specify (and do if-then logic on) every instance/type of control that might receive normal alphabetical key presses (not just the TextBox controls, though they are the worst offenders).


回答1:


Simply check what the OriginalSource is in your KeyDown event handler on 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 are using InputBindings, experiment with setting e.Handled = true in either the KeyDown or the PreviewKeyDown event on your Window, rather than the individual controls. In anyway, I think OriginalSource is the key to your answer. (I swear that was not a pun).




回答2:


There is an event when you handle KeyDown event and it should pass you a KeyEventArgs. From there you can set the Handled to true so that it won't bubble up.

Sample

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


来源:https://stackoverflow.com/questions/24872940/how-do-i-stop-wpf-keydown-events-from-bubbling-up-from-certain-contained-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!