在WPF密钥处理程序中,我可以以编程方式更改/覆盖按下的键吗?

时间:2011-09-19 23:47:52

标签: wpf event-handling keyboard-events

正如标题中所述,我们试图拦截一个密钥并将其替换为另一个密钥。与密钥重新映射类似。

我们的具体用法是将左右箭头键分别改为Shift-Tab和Tab。

现在我知道我可以拦截那些并手动控制焦点,但我试图尽可能多地利用内置的导航行为。我们只想(也)使用箭头键来表示这种行为。

我唯一想到的就是吞下这个事件,然后用正确的参数重新抛出它,但我担心这会干扰关键释放,重复等事情。

如果实际上不可行,我也会采取其他方式。同样,我们的目标是通过其他键来利用内置行为。

1 个答案:

答案 0 :(得分:3)

由于您的目标是映射箭头键以执行某些键盘选项卡导航,因此您应该将相应的命令映射到键并实现它们。 ComponentCommands.MoveFocusForwardComponentCommands.MoveFocusBack命令在这里是合适的,因为我们正在做的事情,将焦点向前移动到下一个控件或者回到上一个控件。

这是一个如何做到这一切的例子。

首先,您需要将命令绑定到您的密钥。

<Window.CommandBindings>
    <CommandBinding Command="ComponentCommands.MoveFocusForward" Executed="MoveFocusForward_Executed" />
    <CommandBinding Command="ComponentCommands.MoveFocusBack" Executed="MoveFocusBack_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
    <KeyBinding Command="ComponentCommands.MoveFocusForward" Key="Right" />
    <KeyBinding Command="ComponentCommands.MoveFocusBack" Key="Left" />
</Window.InputBindings>

然后实现处理程序。

private static bool RequestFocusChange(FocusNavigationDirection direction)
{
    var focused = Keyboard.FocusedElement as UIElement;
    if (focused != null)
    {
        return focused.MoveFocus(new TraversalRequest(direction));
    }
    return false;
}

private void MoveFocusForward_Executed(object target, ExecutedRoutedEventArgs e)
{
    RequestFocusChange(FocusNavigationDirection.Next);
}

private void MoveFocusBack_Executed(object target, ExecutedRoutedEventArgs e)
{
    RequestFocusChange(FocusNavigationDirection.Previous);
}
相关问题