此示例演示如何检测键盘上何时按下 Enter 键。
此示例由可扩展应用程序标记语言(XAML)文件和代码隐藏文件组成。
示例:
当用户在 Enter中按下 TextBox 键时,文本框中的输入将显示在用户界面(UI)的另一区域。
以下 XAML 创建了用户界面,该用户界面由一个 StackPanel、一个 TextBlock 和一个 TextBox 组成。
<StackPanel>
<TextBlock Width="300" Height="20" Text="Type some text into the TextBox and press the Enter key." />
<TextBox Width="300" Height="30" Name="textBox1" KeyDown="textBox1_KeyDown" />
<TextBlock Width="300" Height="100" Name="textBlock1" />
</StackPanel>
后面的代码创建了 KeyDown 事件处理程序。 如果按下的键是 Enter 键,则会在 TextBlock中显示一条消息。
private void textBox1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
textBlock1.Text = $"You Entered: {textBox1.Text}";
}
}
Private Sub textBox1_KeyDown(sender As Object, e As System.Windows.Input.KeyEventArgs)
If e.Key = Key.Return Then
textBlock1.Text = "You Entered: " + textBox1.Text
End If
End Sub