【问题标题】:Get Keyboard state in Universal Windows Apps在通用 Windows 应用程序中获取键盘状态
【发布时间】:2015-12-23 06:25:14
【问题描述】:

我想检测 Windows 应用程序中的组合键(例如 Control-A)。 KeyDown 事件处理程序包含有关最后按下的键的信息。但是如何确定是否也按下了 Control 键?

【问题讨论】:

  • 通常你会这样做KeyPressed == Control | A
  • @KevinKal 谢谢。但我试过了。只是A
  • Control 是一个系统密钥,因此它的记录方式不同。我不确定它是如何完成的,但这就是您看到的问题
  • @rmn36 是的。在 WPF 中,我们可以为此使用 Keyboard 类。不幸的是,在 UWP 中无法访问。
  • Windows 挂钩?很抱歉我从未在 UWP 工作过

标签: c# .net xaml win-universal-app uwp


【解决方案1】:

你可以用CoreVirtualKeyStates.HasFlag(CoreVirtualKeyStates.Down)来判断是不是Ctrl键被按下了,像这样-

Window.Current.CoreWindow.KeyDown += (s, e) =>
{
    var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
    if (ctrl.HasFlag(CoreVirtualKeyStates.Down) && e.VirtualKey == VirtualKey.A)
    {
        // do your stuff
    }
};

【讨论】:

  • 如果我正确理解您的问题,不要订阅您页面的KeyDown 事件,而是订阅Window.Current.CoreWindow.KeyDown,就像我的回答一样。
  • 完美!非常感谢!
【解决方案2】:

您可以使用 AcceleratorKeyActivated 事件,无论焦点在哪里,它都会始终捕获该事件。

public MyPage()
{
    Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += AcceleratorKeyActivated;
}


private void AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
    if (args.EventType.ToString().Contains("Down"))
    {
        var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
        if (ctrl.HasFlag(CoreVirtualKeyStates.Down))
        {
            switch (args.VirtualKey)
            {
                case VirtualKey.A:
                    Debug.WriteLine(args.VirtualKey);
                    Play_click(sender, new RoutedEventArgs());
                    break;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 1970-01-01
    • 2015-12-19
    • 2016-05-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    相关资源
    最近更新 更多