Search code examples
uwpwin-universal-app

UWP KeyboardAccelerator of functions


I know how to add KeyboardAccelerators to UIElements, but can they exist without a UIElement? I just want the Keyboard combo to activate a function.

For example, I want the user to trigger a function called moveFiveSecsAhead() when pressing right and moveFiveSecsBack() when pressing left.

How can I achieve that? One possible solution I can think of is to add two invisible buttons. But is there an easier solution?

---Update---

So I added this piece of code to my control, and it seems that it works well in the debug mode but causes crash in release mode. Why is that?

var left = new KeyboardAccelerator() { Key = Windows.System.VirtualKey.Left };
left.Invoked += (sender, args) => MediaHelper.Position = Math.Max(MediaHelper.Position - 5, 0);
var right = new KeyboardAccelerator() { Key = Windows.System.VirtualKey.Right };
right.Invoked += (sender, args) => MediaHelper.Position = Math.Min(MediaHelper.Position + 5, CurrentMusic.Duration);
this.KeyboardAccelerators.Add(left);
this.KeyboardAccelerators.Add(right);

Solution

  • You can add your keyboard accelerators to the Page you are using and no need for adding two invisible buttons.

    MainPage.xaml.cs

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            var accelerator = new KeyboardAccelerator() { Key = , Modifiers= };
            accelerator.Invoked += moveFiveSecsBack;
            var accelerator1 = new KeyboardAccelerator() { Key = , Modifiers = };
            accelerator.Invoked += moveFiveSecsAhead;
            this.KeyboardAccelerators.Add(accelerator);
            this.KeyboardAccelerators.Add(accelerator1);
        }
        private void moveFiveSecsBack(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
        {
            throw new NotImplementedException();
        }
        private void moveFiveSecsAhead(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
        {
            throw new NotImplementedException();
        }
    }
    

    I hope this helps.