Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Keyboard state in Universal Windows Apps

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?

like image 585
ispiro Avatar asked Sep 25 '15 12:09

ispiro


2 Answers

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
    }
};
like image 123
Justin XL Avatar answered Oct 27 '22 15:10

Justin XL


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;
            }
        }
    }
}
like image 33
ac-lap Avatar answered Oct 27 '22 14:10

ac-lap