#637 – Block Repeating Keys by Setting Handled to true

In a keypress event handler, the IsRepeat property indicates whether the current keypress is a result of a character that is repeating because the user is holding the key down.  If you want to prohibit the use of repeating keys in a control, you can check this property and set the Handled property to true if IsRepeat is true.

Let’s say that we want to prohibit repeating characters in a TextBox.  We can do this by adding logic to a handler for the PreviewKeyDown event.  We don’t do this in the KeyDown event, since the TextBox will swallow this event for certain keys.

We define the handler in XAML.

<TextBox HorizontalAlignment="Center" Width="150" Margin="10"
         PreviewKeyDown="TextBox_PreviewKeyDown" />

We then set Handled based on the value of IsRepeat.

        private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
            e.Handled = e.IsRepeat;

#584 – Handling an Event That Has Already Been Handled

When a routed event in WPF is being routed up or down the hierarchy of elements, an element that handles a particular event can choose to optionally mark the event as handled, by setting the KeyEventArgs.Handled property to true.  Normally, this short-circuits the routing of the event and elements further up (or down) the tree will not see the event.

But you can choose to override this default behavior, setting up an event handler that will get called even when the underlying event has been handled.

You can ask to by notified of handled events by adding an event in code, rather than declaring it in XAML.  The third parameter indicates that this handler should be called even when the event has already been marked as handled.

        public MainWindow()

            spMain.AddHandler(UIElement.KeyDownEvent, (KeyEventHandler)spMain_KeyDown, true);

#583 – Interrupting the Routing Process

We saw that a routed event in WPF can be routed up or down the logical and visual trees, being seen by any element in the hierarchy that chooses to handle the event.

In the diagram below, a KeyDown event is routed up the tree.

Any of the event handlers that intercept this event can choose to indicate that they have handled the event, by setting the Handled property of the KeyEventArgs argument to true.  When this happens, the event will not continue propagating up (or down) the tree.

        private void tbLawrence_KeyDown(object sender, KeyEventArgs e)
            DumpInfo("tbLawrence_KeyDown", sender, e.Source);

        private void spLawrence_KeyDown(object sender, KeyEventArgs e)
            DumpInfo("spLawrence_KeyDown", sender, e.Source);
            e.Handled = true;    // The event stops here

        private void spMain_KeyDown(object sender, KeyEventArgs e)
            DumpInfo("spMain_KeyDown", sender, e.Source);

        private void winMain_KeyDown(object sender, KeyEventArgs e)
            DumpInfo("winMain_KeyDown", sender, e.Source);