1. 程式人生 > >WPF-鍵盤事件

WPF-鍵盤事件

通過一個demo來了解鍵盤事件
設計程式碼

<Window x:Class="keyboard.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="397" Width="360">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition
Height="Auto">
</RowDefinition> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> </Grid.RowDefinitions> <DockPanel> <TextBlock Margin="3" > Type here: </TextBlock
>
<TextBox Name="TextBox" PreviewKeyDown="KeyEvent" KeyDown="KeyEvent" PreviewTextInput="TextBox_PreviewTextInput" PreviewKeyUp="KeyEvent" KeyUp="KeyEvent" TextChanged="TextBox_TextChanged" ></TextBox> </DockPanel> <ListBox Grid.Row="1" Name="listMessage"
Margin="5" />
<Button Grid.Row="2" HorizontalAlignment="Right" Padding="3" Margin="5" Click="Button_Click">Clear List</Button> </Grid> </Window>

邏輯程式碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace keyboard
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void KeyEvent(object sender, KeyEventArgs e)
        {
            string message = "Event:" + e.RoutedEvent + "  " + "Key:" + e.Key;
            this.listMessage.Items.Add(message);
        }

        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            string message = "Event:" + e.RoutedEvent + "  " + "Text:" + e.Text;
            this.listMessage.Items.Add(message);
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            string message = "Event:" + e.RoutedEvent + "  " + "Text:" + e.Changes;
            this.listMessage.Items.Add(message);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.TextBox.Text = "";
            this.listMessage.Items.Clear();
        }



    }
}

當在定義的TextBox輸入K時,顯示如下
這裡寫圖片描述