WPF-键盘事件

2024-04-23 18:15:20 浏览数 (3)

通过一个demo来了解键盘事件 设计代码

代码语言:javascript复制
<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>

逻辑代码

代码语言:javascript复制
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时,显示如下

这里写图片描述这里写图片描述

0 人点赞