Get Keyboard state in Universal Windows Apps

最后都变了- 提交于 2019-12-18 20:52:10

问题


I want to detect a key combination (e.g. Control-A) in a Windows App. The KeyDown event handler has information about the last key pressed. But how do I find out whether the Control key is pressed as well?


回答1:


You can use CoreVirtualKeyStates.HasFlag(CoreVirtualKeyStates.Down) to determine is the Ctrl key has been pressed, like this -

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
    }
};



回答2:


You can use AcceleratorKeyActivated event, irrespective of where the focus is it will always capture the event.

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;
            }
        }
    }
}


来源:https://stackoverflow.com/questions/32781864/get-keyboard-state-in-universal-windows-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!