跳到主要內容

[WPF]如何在程式中加入Hot key event



假設今天我想要讓使用者Hot key(如Alt) trigger程式做事情的時候

我們可以編寫UI的xaml

加入  PreviewKeyDown 事件的handler
並實作他


Step 1. Add event handler
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
        xmlns:conv="clr-namespace:Solution.Converter"
        x:Class="Solution.MainWindow"
        WindowState="Maximized" WindowStyle="None"
        SnapsToDevicePixels="True"
        d:DesignWidth="800" d:DesignHeight="600"
        Loaded="Window_Loaded"
        PreviewKeyDown="Window_PreviewKeyDown"


Step 2. Implement event handler

    // Release the Alt key
        private void Window_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.SystemKey == Key.LeftAlt || e.SystemKey == Key.RightAlt)
              { //implement....
        }

留言