此範例示範如何在使用者於鍵盤上按下 Enter 鍵時偵測到此動作。
這個範例包含 Extensible Application Markup Language (XAML) 檔案和程式碼後置檔案。
範例
當使用者於 TextBox 中按下 Enter 鍵時,文字輸入框中的輸入會出現在使用者介面 (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>
將下列程式碼後方建立 MouseMove 事件處理常式。 如果按下的按鍵是 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