Page-global keyboard events in Windows Store Apps

后端 未结 2 470
無奈伤痛
無奈伤痛 2020-12-30 03:19

I\'m working on a game, a Windows Store App based on WPF and written in C#. When the player presses the Esc key, I want to pause the game and show a menu (Continue, Quit etc

2条回答
  •  误落风尘
    2020-12-30 04:07

    CoreWindow.GetForCurrentThread().KeyDown will not capture events if it the focus is on some other grid/webView/text box, so instead 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;
                }
            }
        }
    }
    

提交回复
热议问题