Gábor Apagyi
Gábor Apagyi

Reputation: 31

Keyboard handling in windows 8 XAML based game

I'm creating a game for Windows Store, using C# and XAML. All my game objects have a canvas, which describe their view. These canvases will be displayed in a canvas (gameRoot).

I want to move my player based on the key he pressed (eg W is go up). Here is my display page:

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

<Canvas x:Name="gameRoot"  KeyDown="gameRoot_KeyDown_1">
    <Button>Vakanu</Button>
</Canvas>


</Page>

I've created a breakpoint in my eventhandler, and KeyDown event never fires. After some google, I figured out, if I create a Button into my Canvas event will fire. But if I remove, event will not fire. If I click anywhere out of the button, event will never fire again.

My question is: how can I create a keyboard event handler, which fires every time when I press a key within a page, not depending which element has the focus?

Upvotes: 3

Views: 1787

Answers (3)

Misty Glotfelter
Misty Glotfelter

Reputation: 63

If you want to handle key press events across the entire page, regardless of focus. Add this c# code to your constructor:

Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;

This subscribes you to any keyDown event that occurs on the page. And of course add the handler:

void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender,     Windows.UI.Core.KeyEventArgs args)
    {
        //Do Something Here.

    }

You can do the same for the KeyUp event.

Upvotes: 1

Spevy
Spevy

Reputation: 1325

Fought with a similar problem a little while ago. You must set your Canvas's "Focusable" property to true. To give your canvas focus, you will need to call the Canvas's Focus() function.

See MSDN Focus Overview really helped me get my head around it.

Upvotes: 0

Filip Skakun
Filip Skakun

Reputation: 31724

You can subscribe to the Window.Current.CoreWindow.KeyDown/Up events.

Upvotes: 4

Related Questions