简体   繁体   中英

How do I suppress menu keyboard shortcut KeyDown handling in WPF?

I have an application that has menu keyboard shortcuts and text boxes. I want the keyboard shortcuts to be disabled when the text box has focus, but I can't figure out an easy way to do this. I could handle the text box's PreviewKeyDown event, but sending a KeyDown event doesn't cause the TextInput event to trigger so I'd have to manually trigger the TextInput event myself, and I'd have to make sure that every text box overrides the PreviewKeyDown event and creates a TextInput event.

Is this the only way suppress menu keyboard shortcuts when a textbox has focus or is there another way that is less error prone?

EDIT:

Here's how I'm adding the keyboard shortcut:

var kgc = new NuiWpfCore.Input.UnrestrictedKeyGestureConverter();  // allows gestures without modifier keys
var result = kgc.ConvertFromString(s) as NuiWpfCore.Input.UnrestrictedKeyGesture;
m_KeyBinding = new KeyBinding();
m_KeyBinding.Command = KeyBindingCommand;
m_KeyBinding.Modifiers = result.Modifiers;
m_KeyBinding.Key = result.Key;
m_Parent.InputBindings.Add(m_KeyBinding); // m_Parent is of type UIElement

Can you provide more inputs as in HOW are you registering the Keyboard shortcuts? Using KeyBinding ? If so it already needs Command specified. So in the Canexecute of the command return false if the textbox is in focus.

This will disable keyboard shortcuts. Some source ocde from your side might be useful.

EDIT

SO now that you have KeyBinding using KeyBindingCommand which look like a RoutedCommand to me. If so do command bindings having CanExecute function.

    m_Parent.CommandBindings.Add(new CommandBinding(KeyBindingCommand, OnExecuted, CanExcute));

In the CanExecute handler.... CanExecutedRoutedArgs may / may not be correct...

    private void CanExecute(object sender, CanExecutedRoutedArgs args)
    {
          e.CanExecute = !textBox.IsFocused;
    } 

The code above is only for illustration.

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