Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking input from a joystick with C# .NET

Tags:

I searched around on Google for this, but the only things I came up with were outdated and did not work.

Does anyone have any information on how to get joystick data using C# .NET?

like image 461
chris12892 Avatar asked Oct 14 '10 03:10

chris12892


1 Answers

Since this was the top hit I got on google while researching joystick / gamepad input in C#, I thought I should post a response for others to see.

The easiest way I found was to use SharpDX and DirectInput. You can install it via NuGet (SharpDX.DirectInput)

After that, it's simply a matter of calling a few methods:

Sample code from SharpDX

static void Main() {     // Initialize DirectInput     var directInput = new DirectInput();      // Find a Joystick Guid     var joystickGuid = Guid.Empty;      foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,                  DeviceEnumerationFlags.AllDevices))         joystickGuid = deviceInstance.InstanceGuid;      // If Gamepad not found, look for a Joystick     if (joystickGuid == Guid.Empty)         foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,                  DeviceEnumerationFlags.AllDevices))             joystickGuid = deviceInstance.InstanceGuid;      // If Joystick not found, throws an error     if (joystickGuid == Guid.Empty)     {         Console.WriteLine("No joystick/Gamepad found.");         Console.ReadKey();         Environment.Exit(1);     }      // Instantiate the joystick     var joystick = new Joystick(directInput, joystickGuid);      Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);      // Query all suported ForceFeedback effects     var allEffects = joystick.GetEffects();     foreach (var effectInfo in allEffects)         Console.WriteLine("Effect available {0}", effectInfo.Name);      // Set BufferSize in order to use buffered data.     joystick.Properties.BufferSize = 128;      // Acquire the joystick     joystick.Acquire();      // Poll events from joystick     while (true)     {         joystick.Poll();         var datas = joystick.GetBufferedData();         foreach (var state in datas)             Console.WriteLine(state);     } } 

I hope this helps.

I even got this to work with a DualShock3 and the MotioninJoy drivers.

like image 167
Valdemar Avatar answered Sep 19 '22 20:09

Valdemar