XNA 4.0中实现简单的快捷键模板

本文详细介绍了如何在XNA游戏中通过键盘快捷键(Alt+Enter)实现全屏与窗口化状态的切换,并提供了封装方法简化操作的示例代码。

 

 

在XNA中,可以通过GraphicsDeviceManager提供的ToggleFullScreen来进行全屏状态转换

通常的游戏中,都会使用Alt+Enter来进行全屏状态切换,所以我们可以在Update中使用如下代码进行全屏切换

   1: protected override void Update(GameTime gameTime)
   2:  
   3: {
   4:  
   5: if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
   6:  
   7: this.Exit();
   8:  
   9: if (Keyboard.GetState()[Keys.RightAlt] == KeyState.Down &&
  10:  
  11: Keyboard.GetState()[Keys.Enter] == KeyState.Down)
  12:  
  13: {
  14:  
  15: graphics.ToggleFullScreen();
  16:  
  17: }
  18:  
  19: base.Update(gameTime);
  20:  
  21: }
  22:  

在里我们使用Keyboard.GetState来获取按键状态

当然我们可以封装起方法来进行操作

   1: protected override void Update(GameTime gameTime)
   2:  
   3: {
   4:  
   5: if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
   6:  
   7: this.Exit();
   8:  
   9: KeyboardTemplate(() => graphics.ToggleFullScreen(), Keys.Enter, Keys.RightAlt);
  10:  
  11: base.Update(gameTime);
  12:  
  13: }
  14:  
  15: void KeyboardTemplate(Action action, params Keys[] keys)
  16:  
  17: {
  18:  
  19: if (keys.Any(key => Keyboard.GetState()[key] != KeyState.Down))
  20:  
  21: {
  22:  
  23: return;
  24:  
  25: }
  26:  
  27: action();
  28:  
  29: }
  30:  

当然我们也可以添加其它一些功能

   1: protected override void Update(GameTime gameTime)
   2:  
   3: {
   4:  
   5: if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
   6:  
   7: this.Exit();
   8:  
   9: KeyboardTemplate(graphics.ToggleFullScreen, Keys.Enter, Keys.RightAlt);
  10:  
  11: KeyboardTemplate(this.Exit, Keys.F4, Keys.LeftControl);
  12:  
  13: base.Update(gameTime);
  14:  
  15: }

这样就可以在Ctrl+F4的时候关闭当前游戏了

转载于:https://www.cnblogs.com/chhlgy/archive/2011/12/27/XNA4_KeyboardTemplate.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值