WPF之键盘输入事件
<Window x:Class="WpfApp2.MainWindow"
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"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="650" Width="400" Initialized="Window_Initialized" Loaded="Window_Loaded" Unloaded="Window_Unloaded" >
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<DockPanel VerticalAlignment="Center">
<Label DockPanel.Dock="Left" HorizontalAlignment="Center"></Label>
<TextBox x:Name="tbInput" PreviewKeyDown="tbInput_PreviewKeyDown" KeyDown="tbInput_KeyDown" PreviewTextInput="tbInput_PreviewTextInput" TextInput="tbInput_TextInput" PreviewKeyUp="tbInput_PreviewKeyUp" KeyUp="tbInput_KeyUp" />
</DockPanel>
<ListBox Grid.Row="1" x:Name="lbMessage"></ListBox>
<CheckBox x:Name="cbIngore" Grid.Row="2" Content="忽略"/>
<Button Click="Button_Click" Grid.Row="3" Height="40" Width="80" Margin="0,0,10,0" VerticalAlignment="Center" HorizontalAlignment="Right" Content="clear"></Button>
</Grid>
</Window>
private void Button_Click(object sender, RoutedEventArgs e)
{
lbMessage.Items.Clear();
}
/// <summary>
/// 预按下事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tbInput_PreviewKeyDown(object sender, KeyEventArgs e)
{
string str = $"{e.RoutedEvent};key:{e.Key}";
lbMessage.Items.Add(str);
}
/// <summary>
/// 按下事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tbInput_KeyDown(object sender, KeyEventArgs e)
{
string str = $"{e.RoutedEvent};key:{e.Key}";
lbMessage.Items.Add(str);
}
private void tbInput_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
string str = $"{e.RoutedEvent};Text:{e.Text}";
lbMessage.Items.Add(str);
}
private void tbInput_TextInput(object sender, TextCompositionEventArgs e)
{
string str = $"{e.RoutedEvent};Text:{e.Text}";
lbMessage.Items.Add(str);
}
private void tbInput_PreviewKeyUp(object sender, KeyEventArgs e)
{
string str = $"{e.RoutedEvent};key:{e.Key}";
lbMessage.Items.Add(str);
}
private void tbInput_KeyUp(object sender, KeyEventArgs e)
{
string str = $"{e.RoutedEvent};key:{e.Key}";
lbMessage.Items.Add(str);
}