#622 – The Source of a Keyboard Event

The source of a keyboard event is the control that had keyboard focus when the key was pressed, referenced by the KeyEventArgs.Source property in a keyboard event handler.  You can consider the source as–the control where the keyboard event is taking place.

The source can be different from the sender of the event, which is the control to which the event handler was attached.

For example, if you have a TextBox contained in a StackPanel and you press a key while the TextBox has focus, the TextBox is the source of the event.  If you then attach a handler for one of the keyboard events to the StackPanel, the StackPanel is the sender of the event.

    <StackPanel KeyUp="StackPanel_KeyUp">
        <TextBox Text="I'm a TextBox" HorizontalAlignment="Center"

#618 – Keyboard Event Summary

The following attached events are defined in the Keyboard class and are exposed as public events of the ContentElement, UIElement and UIElement3D classes:

  • PreviewKeyDown / KeyDown – Key is pressed  (KeyEventArgs)
  • PreviewKeyUp / KeyUp  – Key is released  (KeyEventArgs)
  • PreviewGotKeyboardFocus / GotKeyboardFocus – Element gains keyboard focus  (KeyboardFocusChangedEventArgs)
  • PreviewLostKeyboardFocus / LostKeyboardFocus – Element loses keyboard focus  (KeyboardFocusChangedEventArgs)

The following attached events are defined in the TextCompositionManager and also exposed as public events of ContentElementUIElement and UIElement3D:

  • PreviewTextInput / TextInput – Element is receiving text  (TextCompositionEventArgs)

Not strictly a keyboard or text composition event, but related, is the following attached event, which is defined in and exposed as a public event from the TextBoxBase class:

  • TextChanged – Content in text box has changed  (TextChangedEventArgs)

Tunneling events (PreviewXyz) are typically paired with a corresponding bubbling event (Xyz).  The tunneling event fires first, going down the logical tree, followed by the bubbling event, which works its way back up the logical tree.