xcoder37
xcoder37

Reputation: 527

Handling Page KeyUp event

I'm writing C#/XAML UWP App.

I want to handle KeyDown event for a whole page in my app. That is, no matter what specific control on the page has focus (e.g. a TextBox, a ListView, etc. ), whenever user presses a key while on that page, I want global for the whole Page KeyDown event to be fired. In theory this should be simple - subscribing to KeyDown event when the page is navigated to or loaded, for example:

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
     KeyDown += SettingsPage_KeyDown;
    }

In practice this does't work for all the pages, even for quite simple ones and I can't understand why. I hooked up Window.Current.CoreWindow.KeyDown event which works always and properly, but I'd like to know what's wrong with Page's KeyDown event. Obviously there may be hundredts of reasons why this doesn't work, but are there any common? I tried setting focus to page (Programmatic, Keyboard) and still there seems to be no rule when this event works and when it doesn't.

Upvotes: 3

Views: 1709

Answers (2)

vvasch
vvasch

Reputation: 366

You could also add the KeyDown attribute in the XAML:

<Page
x:Class="WESS1.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WESS1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" KeyDown="SettingsPage_KeyDown">

And in the code behind file:

public sealed partial class SettingsPage: Page
{
    public SettingsPage() //Constructor
    {
       this.InitializeComponent();   
    }

    private void SettingsPage_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        // e.g. check the value of e.Key
    }
}

Upvotes: 0

Juan Carlos Velez
Juan Carlos Velez

Reputation: 2940

I am using the next code in an application for Windows IoT, and it works:

public sealed partial class YourPage: Page
{
    public YourPage() //Constructor
    {
       this.InitializeComponent();

       //Add this line
       Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;    
    }

    void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
    {
        //todo
    }
}

Upvotes: 3

Related Questions