UWP 響應鍵盤組合快捷鍵

星期八再娶你發表於2018-04-20

方法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,根據實際情況更改。

 

 

參考:http://www.songshizhao.com/blog/blogPage/405.html

 

相關文章