Keyboard.KeyDown Attached Event

Definition

按下鍵盤上的按鍵時發生。Occurs when a key on the keyboard is pressed.

see AddKeyDownHandler, and RemoveKeyDownHandler
see AddKeyDownHandler, and RemoveKeyDownHandler
see AddKeyDownHandler, and RemoveKeyDownHandler

Examples

下列範例會建立 TextBox,以附加 KeyDown 事件的事件處理常式。The following example creates TextBox that attaches an event handler for the KeyDown event. 當按下 Return 時,事件處理常式會在 TextBlock中顯示 TextBox 中的文字。When the Return is pressed, the event handler displays the text in the TextBox in a TextBlock.

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

Remarks

這是附加事件。This is an attached event. WPFWPF 將附加事件實作為路由事件。implements attached events as routed events. 附加事件基本上是一種 XAMLXAML 的語言概念,可以在未定義該事件的物件上處理這些事件,而這 WPFWPF 會藉由同時讓事件通過路由來進行擴充。Attached events are fundamentally a XAMLXAML language concept for referencing events that can be handled on objects that do not define that event, which WPFWPF expands upon by also enabling the event to traverse a route. 附加事件在程式碼中沒有直接處理語法;若要在程式碼中附加路由事件的處理常式,您可以使用指定的 Add * 處理常式方法。Attached events do not have a direct handling syntax in code; to attach handlers for a routed event in code, you use a designated Add*Handler method. 如需詳細資訊,請參閱附加事件總覽For details, see Attached Events Overview.

路由事件資訊Routed Event Information

識別碼欄位Identifier field KeyDownEvent
路由策略Routing strategy 路由Bubbling
委派Delegate KeyEventHandler

Applies to

See also