#631 – Event Sequence for KeyPressUp, KeyPressDown and TextInput

The full event sequence for keyboard related events is shown below, as they propagate down (tunneling) or up (bubbling) the logical tree.

If we have a Window that contains a StackPanel, which in turn contains a TextBox, the sequence of events would be:

  • Window_PreviewKeyDown
  • StackPanel_PreviewKeyDown
  • TextBox_PreviewKeyDown
  • TextBox_KeyDown
  • StackPanel_KeyDown
  • Window_KeyDown
  • Window_PreviewTextInput
  • StackPanel_PreviewTextInput
  • TextBox_PreviewTextInput
  • TextBox_TextInput – suppressed/handled
  • StackPanel_TextInput – suppressed/handled
  • Window_TextInput – suppressed/handled
  • Window_PreviewKeyUp
  • StackPanel_PreviewKeyUp
  • TextBox_PreviewKeyUp
  • TextBox_KeyUp
  • StackPanel_KeyUp
  • Window_KeyUp

Note that the TextInput event is listed, since TextInput events would normally fire for the originating control and then propagate up the logical tree.  But in the case of TextBox, the TextInput event is marked as handled and therefore does not fire.

#630 – PreviewTextInput and TextInput Events

In addition to the four main keypress events–PreviewKeyDown, KeyDownPreviewKeyUp and KeyUp–an UIElement can fire two other events related to keyboard input.  Both fire when the user presses a key, or combination of keys, that results in the control receiving some text.  They do not fire when keys are pressed that don’t result in the keyboard sending text (e.g. the Backspace key).

Here’s the updated sequence of events:

  • PreviewKeyDown – tunneling
  • KeyDown – bubbling
  • PreviewTextInput  – tunneling
  • TextInput – bubbling
  • PreviewKeyUp – tunneling
  • KeyUp – bubbling

Note that controls that normally accept text and do something with it will suppress the TextInput event, marking it as handled.  For example, the TextBox control takes the text input and adds it to to the TextBox, so it marks TextInput as already handled.  The TextBox is saying that it already “handled” the text, so it doesn’t need to pass the event on to anybody else.