2017-03-11 71 views
0

我在C#中的Windows通用應用程序上開發遊戲。我在界面上有四個按鈕(左,右,上,下)來移動我地圖上的角色。當按下按鍵時激活按鈕C#通用應用程序

我的問題是:如何激活我的功能用鍵盤箭頭移動()?

我嘗試了很多的解決方案,從網絡獲取鍵被按下,但大多數的哦,關心他們唯一的輸入形式...

回答

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移動。

如果沒有代碼的概念,請和我說說話。

+0

非常感謝! – K4tn1x

相關問題