Condividi tramite


Procedura: Rilevare quando viene premuto il tasto INVIO

In questo esempio viene illustrato come rilevare quando viene premuto il tasto Enter sulla tastiera.

Questo esempio è costituito da un file XAML (Extensible Application Markup Language) e da un file code-behind.

Esempio

Quando l'utente preme il tasto Enter nella TextBox, i dati inseriti nella casella di testo vengono visualizzati in un'altra area dell'interfaccia utente.

Il codice XAML seguente crea l'interfaccia utente, costituita da un StackPanel, un TextBlocke un 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>

Il code-behind seguente crea il gestore eventi KeyDown. Se il tasto premuto è il tasto Enter, viene visualizzato un messaggio nella 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

Vedere anche