Search code examples
c#windowsuwpwin-universal-appwindows-10-universal

Disable interaction of UWP app with the Tab Key


I am building a UWP app. I want that my app does not respond to the Tab Key at all. I mean that my app should completely ignore whenever the user presses the Tab key.


Solution

  • You can handle the Tab key in the PreviewKeyDown event of your page:

    public MainPage()
    {
        this.InitializeComponent();
        this.PreviewKeyDown += MainPage_PreviewKeyDown;
    }
    
    private void MainPage_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == VirtualKey.Tab)
        {
            e.Handled = true;
        }
    }
    

    However, I would advise against that, because this removes an important part of the accessibility of your app - many users like to or need to use keyboard to navigate.

    Application-wide solution

    If you want to handle the Tab key application-wide, you can do that in two ways:

    Create a custom base page type

    You can create a new class like PageBase which will derive from Page and will have the PreviewKeyDown event handling set up in its constructor. All other pages you will have in your app can then derive from PageBase.

    Handling Tab on root Frame

    You can add PreviewKeyDown handler to the app's root Frame control in App.xaml.cs:

    rootFrame = new Frame();
    rootFrame.PreviewKeyDown += RootFrame_PreviewKeyDown;