WPF 等效于 Winform 的 KeyEventArgs - 使用特定键调用 KeyDown-event



如何转换以下与Winforms一起工作的代码,使其与WPF:一起工作

textBox1.Text = (input); 
KeyEventArgs ev = new KeyEventArgs(Keys.Enter);
textBox1_KeyDown(sender, ev);

我想用一个特定的键调用KeyDown事件,以便在textBox1中自动输入一个特定值。

要订阅TextBoxKeyDown-事件,可以使用以下方法之一:

方法1-使用XAML定义事件(不需要手动订阅事件(:

XAML:

<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<!-- define your TextBox and the KeyDown-event here -->
<TextBox x:Name="MyTextBox" Width="120" Height="30" KeyDown="MyTextBox_KeyDown"/>
</Grid>
</Window>

C#-代码:

using System.Windows;
using System.Windows.Input;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{ 
// if pressed key is "Enter", do something
if (e.Key == Key.Enter)
{
this.MyTextBox.Text = "Some Text!";
}
}
}
}

方法2-定义事件并使用代码订阅:

XAML:

<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<!-- define your TextBox here -->
<TextBox x:Name="MyTextBox" Width="120" Height="30"/>
</Grid>
</Window>

C#-代码:

using System.Windows;
using System.Windows.Input;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
this.MyTextBox.KeyDown += this.MyTextBox_KeyDown;
}
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{ 
// if pressed key is "Enter", do something
if (e.Key == Key.Enter)
{
this.MyTextBox.Text = "Some Text!";
}
}
}
}

要使用特定密钥(此处:Key.Enter(调用KeyDown-事件,可以使用:

using System;
using System.Windows.Interop;
KeyEventArgs enterPressedArgs = new KeyEventArgs(Keyboard.PrimaryDevice, new HwndSource(0, 0, 0, 0, 0, "", IntPtr.Zero), 0, Key.Enter);
this.MyTextBox_KeyDown(null, enterPressedArgs);

最新更新