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

前端 未结 2 937
庸人自扰
庸人自扰 2021-02-20 12:57

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, Combo

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-20 13:26

    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).

提交回复
热议问题