按下键时激活按钮C#Universal App

时间:2017-03-11 22:32:56

标签: c# win-universal-app keyboard-events

我使用C#在Windows Universal App上开发游戏。我的界面上有四个按钮(左,右,上,下)来移动地图上的角色。

我的问题是:如何使用键盘箭头激活我的函数Move()?

我尝试了很多来自网络的解决方案来获取按键,但大多数情况下他们只关注输入表格......

1 个答案:

答案 0 :(得分:1)

您可以使用KeyDown激活键盘。

xaml是

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

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" KeyDown="Grid_OnKeyDown">
        <Button x:Name="btn" Content="K">
            <Button.RenderTransform>
                <CompositeTransform></CompositeTransform>
            </Button.RenderTransform>
        </Button>
        <Grid VerticalAlignment="Bottom">
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Button Grid.Row="0" Grid.Column="0" Content="left" Click="Button_OnClick"></Button>
            <Button Grid.Row="1" Grid.Column="0" Content="up" Click="Button_OnClick"></Button>
            <Button Grid.Row="0" Grid.Column="1" Content="down" Click="Button_OnClick"></Button>
            <Button Grid.Row="1" Grid.Column="1" Content="right" Click="Button_OnClick"></Button>
        </Grid>
    </Grid>
</Page>

它将上下移动btn使用按钮。

你应该写代码:

   private void Grid_OnKeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == VirtualKey.Left)
        {
            Move(-1, 0);
        }
        else if (e.Key == VirtualKey.Right)
        {
            Move(1, 0);
        }
        else if (e.Key == VirtualKey.Up)
        {
            Move(0, -1);
        }
        else if (e.Key == VirtualKey.Down)
        {
            Move(0, 1);
        }
    }

    private void Move(int x, int y)
    {
        var temp = btn.RenderTransform as CompositeTransform;
        temp.TranslateX += x;
        temp.TranslateY += y;
    }

    private void Button_OnClick(object sender, RoutedEventArgs e)
    {
        var b = sender as Button;
        if (b != null)
        {
            string str = b.Content as string;
            if (str == "up")
            {
                Move(0, -1);
            }
            else if (str == "down")
            {
                Move(0, 1);
            }
            else if (str == "left")
            {
                Move(-1, 0);
            }
            else if (str == "right")
            {
                Move(1, 0);
            }
        }
    }
}

你应该使用Grid.KeyDown获取密钥并使btn移动。

如果没有代码概念,请与我联系。