[英]Activate button when key is pressed C# Universal App
我使用C#在Windows Universal App上開發了一個游戲。 我的界面上有四個按鈕(向左,向右,向上,向下),以在地圖上移動角色。
我的問題是:如何也使用鍵盤箭頭激活我的功能Move()?
我從網絡上嘗試了很多解決方案以使按鍵被按下,但大多數情況下,它們僅涉及輸入形式...
您可以使用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移動。
如果沒有代碼概念,請談談。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.