C# Обработываем событие на Hotkey в приложениях WPF

Способ 1

        public MainWindow()
        {
            InitializeComponent();
            AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent);
        }

        private void HandleKeyDownEvent(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
            {
                MessageBox.Show("CTRL + SHIFT + TAB trapped");
            }

            if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                MessageBox.Show("CTRL + TAB trapped");
            }
        }



Способ 2

<Window x:Class="WPFHotkey.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPFHotkey"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="local:MainWindow.Some_Command" Executed="Some_Executed"/>
    </Window.CommandBindings>
    <Window.InputBindings>
        <KeyBinding Key="F4" Modifiers="ALT" Command="local:MainWindow.Some_Command"/>
    </Window.InputBindings>
    <Grid>
        
    </Grid>
</Window>


using System.Windows;
using System.Windows.Input;

namespace WPFHotkey
{
    
    public partial class MainWindow : Window
    {
        public static RoutedCommand Some_Command = new RoutedCommand();


        private void Some_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Hi!");
        }

        public MainWindow()
        {
            InitializeComponent();
        }

    }
}

No comments:

Post a Comment