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时,显示如下
这里写图片描述

猜你喜欢

转载自blog.csdn.net/maybe_ch/article/details/80596293