Como detectar quando a tecla Enter é pressionada

Este exemplo mostra como detectar quando a Enter tecla é pressionada no teclado.

Este exemplo consiste em um arquivo XAML (Extensible Application Markup Language) e um arquivo code-behind.

Exemplo

Quando o usuário pressiona a tecla no TextBox, a Enter entrada na caixa de texto aparece em outra área da interface do usuário (UI).

O XAML a seguir cria a interface do usuário, que consiste em um , a TextBlocke um StackPanelTextBox.

<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>

O code-behind a seguir cria o manipulador de KeyDown eventos. Se a tecla pressionada for a Enter tecla , uma mensagem será exibida no TextBlock.

private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        textBlock1.Text = "You Entered: " + textBox1.Text;
    }
}
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

Confira também