如何:检测何时按下 Enter 键
更新:2007 年 11 月
此示例演示如何检测何时按下键盘上的 Enter 键。
本示例包括一个可扩展应用程序标记语言 (XAML) 文件和一个代码隐藏文件。有关完整示例,请参见键盘按键示例。
示例
当用户在 TextBox 中按下 Enter 键时,文本框中的输入将显示在用户界面 (UI) 的其他区域。
下面的 XAML 创建了用户界面,其中包括一个 StackPanel、一个 TextBlock 和一个 TextBox。
<StackPanel>
<TextBlock Width="300" Height="20">
Type some text into the TextBox and press the Enter key.
</TextBlock>
<TextBox Width="300" Height="30" Name="textBox1"
KeyDown="OnKeyDownHandler"/>
<TextBlock Width="300" Height="100" Name="textBlock1"/>
</StackPanel>
下面的代码隐藏创建 KeyDown 事件处理程序。 如果按下的键是 Enter 键,则在 TextBlock 中会显示一条消息。
Private Sub OnKeyDownHandler(ByVal sender As Object, ByVal e As KeyEventArgs)
If (e.Key = Key.Return) Then
textBlock1.Text = "You Entered: " + textBox1.Text
End If
End Sub
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
textBlock1.Text = "You Entered: " + textBox1.Text;
}
}