简体   繁体   中英

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#. 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. 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. But let's say you press X for one second = it detects X was "pressed" 100 times because well, every 10ms, X was pressed. 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#? If so, how? If not, is there a better/lower latency XInput wrapper for C# that will do what I need?

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. The 1st if statement will not be true again until the button is release and re-pressed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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