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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: