UWP响应键盘组合快捷键

关键词:

当前uwp不支持注册全局热键,但可以在应用内部响应windows的shortcut。

在uwp内检测快捷键2种方式如下:

方法1:响应Ctrl+?快捷键

首先在load事件或者keydown事件内注册事件


public MainPage()
        {
            this.InitializeComponent();
            // Register for accelerator key events used for button hotkeys
            Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += Dispatcher_AcceleratorKeyActivated;
        }


注册的事件如下(检测Ctrl+V和Ctrl+N):


        private void Dispatcher_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.V:
                            ViewOrders_Tapped(this, null);
                            break;
                        case VirtualKey.N:
                            NewOrder_Tapped(this, null);
                            break;
                    }
                }
            }
        }


方法2:响应Ctrl+鼠标滚轮

        private void WheelChanged(object sender, PointerRoutedEventArgs e)
        {
            RichEditBox editor = sender as RichEditBox;
            var x = e.GetCurrentPoint(editor).Properties.MouseWheelDelta;
            var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
            if (ctrl.HasFlag(CoreVirtualKeyStates.Down))
            {
                if (x > 0)
                {
                    redit.Document.Selection.CharacterFormat.Size += 1;
                }
                else
                {
                    redit.Document.Selection.CharacterFormat.Size -= 1;
                }
                e.Handled = true;//取消内容滚动
            }
        }

说明:所有UI元素都具有PointerWheelChanged事件,响应此事件同时判断Ctrl状态判断用户操作。例子中响应的UIElement元素为RichEditBox,根据实际情况更改。

作者:songshizhao 发表于:2017-11-24T07:47:56 访问量:1679
评论 [发表评论]