Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading