Quantcast
Channel: 2,000 Things You Should Know About WPF » Handled
Viewing all articles
Browse latest Browse all 3

#637 – Block Repeating Keys by Setting Handled to true

$
0
0

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

Filed under: Events Tagged: Events, Handled, IsRepeat, PreviewKeyDown, WPF

Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images