按下按钮上的SlimDx事件

时间:2016-07-06 08:54:43

标签: c# slimdx

我使用slimdx来解释xbox控制器按钮按下。我每隔200ms轮询一次读取xbox按钮的状态,所有这些都适用于我。我用

        JoystickState state = Joystick.GetCurrentState();
        // get buttons states
        bool[] buttonsPressed = state.GetButtons();

是否有按钮按下而不是轮询生成事件?如果我的民意调查时间是5秒,想象一下。并且用户在第二秒按下按钮并释放它。在下一个轮询时间,我的应用程序永远不会知道按下按钮

2 个答案:

答案 0 :(得分:2)

不 - 在DirectX中你必须进行民意调查。为了有效地执行此操作,您需要创建一个轮询线程,并且有一个类将交叉线程事件引发到您的消费线程。

答案 1 :(得分:0)

我知道这是4岁,但是答案不正确。最有效的方法可能是轮询,但是您可以在轮询时引发事件。

这是一项正在进行的工作,但应该可以使某人入门。将其保存为新类,它是从Timer派生的,因此一旦将其添加到项目中,进行构建并将其拖动到要使用的Form上,即可订阅buttonPressed事件。

public class GamePadController : Timer
{

    public delegate void ButtonPressedDelegate(object sender, int ButtonNumber);
    public event ButtonPressedDelegate ButtonPressed;

    List<DeviceInstance> directInputList = new List<DeviceInstance>();
    DirectInput directInput = new DirectInput();
    List<SlimDX.DirectInput.Joystick> gamepads = new List<Joystick>();
    SlimDX.DirectInput.JoystickState state;



    public GamePadController()
    {
        this.Interval = 10;
        this.Enabled = true;
        this.Tick += GamePadController_Tick;
        RefreshGamePads();
        
    }


    private void RefreshGamePads()
    {
        directInputList.Clear();
        directInputList.AddRange(directInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly));
        gamepads.Clear();
        foreach (var device in directInputList)
        {
            gamepads.Add(new SlimDX.DirectInput.Joystick(directInput, directInputList[0].InstanceGuid));
        }
    }

    private void GamePadController_Tick(object sender, EventArgs e)
    {
        
        foreach (var gamepad in gamepads)
        {
            if (gamepad.Acquire().IsFailure)
                continue;
            if (gamepad.Poll().IsFailure)
                continue;
            if (SlimDX.Result.Last.IsFailure)
                continue;

            state = gamepad.GetCurrentState();

            bool[] buttons = state.GetButtons();

            for (int i = 0; i < buttons.Length; i++)
            {
                if (buttons[i])
                {
                    if (ButtonPressed != null)
                    {
                        ButtonPressed(gamepad, i);
                    }
                }
            }

            gamepad.Unacquire();
        }

    }
}
}
相关问题