michielpost.nl

Disable beep on enter in Windows 8 / WinRT

08-04-2012

This blog post is about Windows 8 / WinRT XAML apps. It's based on the Windows 8 Consumer Preview, things can still change in upcoming versions.

The default behaviour of a TextBox in a Windows 8 XAML application when pressing enter is a BEEP sound. This might be ok, if you're just entering data and are not able to submit anything. But if you're using the textbox as a search field, the beep is not really user friendly.

How to remove the beep when pressing enter in a textbox?

In previous frameworks (WPF, WinForms etc) it was enough to listen to the keydown event, detect the enter key and cancel the event by setting:

if (e.KeyCode == Keys.Enter)
{
 e.SuppressKeyPress = true;

 OR e.Handled = True
}

This does not work with Windows 8 / WinRT xaml apps!

It turns out you have to create your own TextBox control, which can inherit from the default TextBox and override the OnKeyDown and OnKeyUp.

You can find a basic implementation below:

public class NoSoundTextBox : TextBox
    {
        protected override void OnKeyDown(Windows.UI.Xaml.Input.KeyEventArgs e)
        {
            //do nothing, just override the original one to avoid the waring sound.
            if(e.Key != Windows.System.VirtualKey.Enter)
                base.OnKeyDown(e);
        }

        protected override void OnKeyUp(Windows.UI.Xaml.Input.KeyEventArgs e)
        {
            //do nothing, just override the original one to avoid the waring sound.
            if (e.Key != Windows.System.VirtualKey.Enter)
                base.OnKeyUp(e);
        }
    }

After that, use the <namespace:NoSoundTextBox /> in XAML instead of the normal <TextBox />

Comments


No comments yet.

New Comment

Name
E-mail (not published)
Comment
Enter the code shown: