WPF-键盘事件

29 篇文章 4 订阅

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Maybe_ch

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值