Detecting gamepad input

Mihai Bratulescu picture Mihai Bratulescu · Nov 1, 2013 · Viewed 7.3k times · Source

Code so far:

Device gamepad;
public bool initializeGamePad()
        {
            foreach ( DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly) )
            {
                gamepad = new Device(di.InstanceGuid);
                break;
            }

            if (gamepad==null)//no gamepads detected
                return false;
            else
            {
                configureGamePad();
                return true;
            }
        }

        public void configureGamePad()
        {
            //Set axis ranges
            foreach (DeviceObjectInstance doi in gamepad.Objects)
            {
                if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                {
                    gamepad.Properties.SetRange(ParameterHow.ById, doi.ObjectId, new InputRange(-5000, 5000));
                }
            }

            //Set joystick axis mode absolute
            gamepad.Properties.AxisModeAbsolute = true;

            //set cooperative level.
            gamepad.SetCooperativeLevel(new Form1(), CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);

            //Acquire devices for capturing
            gamepad.Acquire();

            UpdateJoystick();
        }

        private void UpdateJoystick()
        {
            string info = "Joystick: ";

            //Get Mouse State
            JoystickState state = gamepad.CurrentJoystickState;

            //Capture Position
            info += "X:" + state.X + " ";
            info += "Y:" + state.Y + " ";
            info += "Z:" + state.Z + " ";
            info += "ARx:" + state. + "\n";

            //Capture Buttons
            byte[] buttons = state.GetButtons();
            for (int i = 0; i < buttons.Length; i++)
            {
                if (buttons[i] != 0)
                {
                    info += "Button:" + i + " ";
                }
            }

            MessageBox.Show(info);
        }

The problem is that the info string contains only the value 0 for state.X/Y/Z and nothing in regards to buttons.

I need something like this: button_down & button_release in order to get 2 or more simultanious buttons pressed. And the axis pozisions.

Also I only use the DirectX SKD no SlimDX or anyting else.

Answer

Will Custode picture Will Custode · Nov 1, 2013

You'll probably have to interface with DirectX in a managed form. Check out this article on SO for more details. But essentially it's just polling for input and then processing your own events. If you have further questions beyond the "how do I get this going" feel free to comment and I'll edit if I can.