Search code examples
wpf.net-corewinui-3winui

WinUI 3 global key down/up events


I would like to handle the Escape button key pressed event in a WinUI 3 application, with MVVM Toolkit. I want to use this event to close the application.

I have tried different solutions, but most of them are talking about an UIElement which must have focus. I have tried the Page KeyDown and KeyUp events, but they only trigger if there is an UIElement in the Page controls, which has focus.

In WPF I could do this by adding a MVVM command with parameter to a KeyBinding in the Windows.InputBindings.

Is there a way to obtain the same functionality in WinUI 3?


Solution

  • You can use KeybordAccelerators for this:

    <Page.KeyboardAccelerators>
        <KeyboardAccelerator
            Key="Escape"
            Invoked="KeyboardAccelerator_Invoked"
            Modifiers="None" />
    </Page.KeyboardAccelerators>
    
    private void KeyboardAccelerator_Invoked(
        KeyboardAccelerator sender,
        KeyboardAcceleratorInvokedEventArgs args)
    {
    }
    

    UPDATE

    If you need to do your process via a command, you can use the Microsoft.Xaml.Behaviors.WinUI.Managed NuGet package.

    <Page
        x:Class="KeyboardAcceleratorsExample.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:core="using:Microsoft.Xaml.Interactions.Core"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:i="using:Microsoft.Xaml.Interactivity"
        xmlns:local="using:KeyboardAcceleratorsExample"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
        mc:Ignorable="d">
    
        <Page.KeyboardAccelerators>
            <KeyboardAccelerator
                Key="Escape"
                Modifiers="None">
                <i:Interaction.Behaviors>
                    <core:EventTriggerBehavior EventName="Invoked">
                        <core:InvokeCommandAction Command="{x:Bind ViewModel.DoSomethingCommand}" />
                    </core:EventTriggerBehavior>
                </i:Interaction.Behaviors>
            </KeyboardAccelerator>
        </Page.KeyboardAccelerators>
    </Page>