简体   繁体   English

C#+ SlimDX / XInput-如何在按下按钮时进行轮询?

[英]C# + SlimDX / XInput - how to poll when button is pressed?

I need to interface with Xbox 360 controllers and my limited knowledge leaves me stuck with C#. 我需要与Xbox 360控制器进行交互,而我的有限知识使我无法使用C#。 I don't want to use XNA (and require users to have it installed) for this simple thing, so I'm using SlimDX to allow me to interface with XInput. 我不想为这个简单的事情使用XNA(并且要求用户安装它),所以我正在使用SlimDX来允许我与XInput交互。 I have been able to detect all button presses and the little program is coming along...but I need to know how to poll / know when a button is pressed, to then trigger events. 我已经能够检测到所有按钮被按下,并且小程序随之出现……但是我需要知道如何轮询/知道何时按下按钮,然后触发事件。

Right now I have a timer running at 10ms and it checks which buttons are pressed and behaves based on that. 现在,我有一个计时器,运行时间为10毫秒,它会检查按下了哪些按钮,并以此为依据进行操作。 But let's say you press X for one second = it detects X was "pressed" 100 times because well, every 10ms, X was pressed. 但是,假设您按下X秒钟=它检测到X被“按下”了100次,因为每10毫秒X被按下一次。 I want to fire up my events only when the button is pressed, and not have to depend on a timer. 我只想在按下按钮时触发事件,而不必依赖计时器。

Is it possible with SlimDX on C#? SlimDX是否可以在C#上使用? If so, how? 如果是这样,怎么办? If not, is there a better/lower latency XInput wrapper for C# that will do what I need? 如果没有,是否有更好/更低延迟的C#XInput包装器可以满足我的需求?

Thanks in advance! 提前致谢!

Create two variables to store the button's state between polls. 创建两个变量以在两次轮询之间存储按钮的状态。

bool curretButtonState;//pressed == true
bool previousButtonState;

//poll each 10ms
void CheckInput()
{
  currentButtonState = pollResult;

  if(currentButtonState == true && previousButtonState == false)
  {
    //button just pressed, call code
  }
  if(currentButtonState== false && previousButtonState == true)//additional functionality if desired
  {
    //button just released, call other code
  }

 previousButtonState = currentButtonState;
}

Let's say it detects a button press and runs your appropriate code, then the next time it polls (10ms), since the previous state was toggled to true, and the button is still pressed, then both states will be true and it wont run the code the 2nd time. 假设它检测到按下按钮并运行您的适当代码,然后在下次轮询(10毫秒)时,由于先前的状态已切换为true,而按钮仍处于按下状态,则两种状态都将为true,并且不会运行第二次编码。 The 1st if statement will not be true again until the button is release and re-pressed. 直到释放并重新按下按钮后,第一个if语句才会再次为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM