2
votes

I've been trying to make this work as part of a game to learn the UWP enviroment when using Canvas. I've read so much on the subject of getting KeyDown to work I'm lost.

Needless to say I hope but none of them seem to work, none cause the event handler to be called.

Any help would be appreciated.

My XAML

    <Grid Background="Black">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Canvas Name="paintCanvas" Background="Black" 
                Grid.Column="1" HorizontalAlignment="Stretch" MaxWidth="642" MaxHeight="422"/>
    </Grid>

My simplified code behind:

namespace Game
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            paintCanvas.KeyDown += new KeyEventHandler(OnKeyDownHandler);
        }


        private void OnKeyDownHandler(object sender, KeyRoutedEventArgs e)
        {
            switch (e.Key)
            {
                case VirtualKey.Down:
                    // do something
                    break;
                case VirtualKey.Up:
                    // do something
                    break;
                case VirtualKey.Left:
                    // do something
                    break;
                case VirtualKey.Right:
                    // do something
                    break;
            }
        }
    }
}
1
Not surprisingly, this won't work. A canvas is a Panel, not a Control, so it's not focus-able. The KeyDown event only applies to an Control with input focus.Jackie
Try declaring a Control(TextBox for instance) inside your canvas, then have it focused. Press the Keyboard to see if the Canvas KeyDown event gets hit.Jackie
Thanks for the comment. How come the canvas has a KeyDown event then (to name one of many events)?? Does the KeyDown event here fire if it occurs in a child control or should the handler be put in the control's KeyDown event property?gaw

1 Answers

0
votes

You can handle this using accelerated keys. You can leverage the KeyHelper in Template 10 if you want some code to steal.

https://github.com/Windows-XAML/Template10/blob/master/Template10%20(Library)/Services/KeyboardService/KeyboardHelper.cs

Then again, you could just use Template 10; in Visual Studio go to Extension Manager and search "Template 10" or add the Template 10 library through Nuget.

Best of luck!