Edit

Share via


How to: Detect When the Enter Key Pressed

This example shows how to detect when the Enter key is pressed on the keyboard.

This example consists of a Extensible Application Markup Language (XAML) file and a code-behind file.

Example

When the user presses the Enter key in the TextBox, the input in the text box appears in another area of the user interface (UI).

The following XAML creates the user interface, which consists of a StackPanel, a TextBlock, and a 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>

The following code behind creates the KeyDown event handler. If the key that is pressed is the Enter key, a message is displayed in the 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

See also