如何在 WPF 中抑制菜单键盘快捷键 KeyDown 处理?
我有一个具有菜单键盘快捷键和文本框的应用程序。我希望当文本框获得焦点时禁用键盘快捷键,但我找不到一种简单的方法来做到这一点。我可以处理文本框的 PreviewKeyDown 事件,但发送 KeyDown 事件不会导致 TextInput 事件触发,因此我必须自己手动触发 TextInput 事件,并且必须确保每个文本框都会覆盖PreviewKeyDown 事件并创建 TextInput 事件。
当文本框具有焦点时,这是抑制菜单键盘快捷键的唯一方法还是有其他不易出错的方法?
编辑:
以下是我添加键盘快捷键的方法:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您能否提供更多输入,例如您如何注册键盘快捷键?使用
KeyBinding
?如果是这样,它已经需要指定Command
。因此,如果文本框处于焦点状态,则在命令的 Canexecute 中返回 false。这将禁用键盘快捷键。您这边的一些源代码可能会有用。
编辑
现在你已经有了使用
KeyBindingCommand
的KeyBinding
,它对我来说看起来像一个RoatedCommand
。如果是这样,则命令绑定具有CanExecute
功能。在
CanExecute
处理程序中...CanExecutedRoulatedArgs
可能/可能不正确...上面的代码仅用于说明。
Can you provide more inputs as in HOW are you registering the Keyboard shortcuts? Using
KeyBinding
? If so it already needsCommand
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
usingKeyBindingCommand
which look like aRoutedCommand
to me. If so do command bindings havingCanExecute
function.In the
CanExecute
handler....CanExecutedRoutedArgs
may / may not be correct...The code above is only for illustration.