AdSense

Friday 12 July 2013

C# - Access joystick

(Deutsche Version) In this post I will show how to access a joystick in C#. I use the joystick project from here, I just put everything into a new Windows Forms project into a class Joystick.cs (DirectX had to be included, more information about that is provided here). I modified the project a bit, more about that later.

My program (e.g. to read the x-axis) looks like this:

public partial class Form1 : Form
{
    Joystick.Joystick joystick;
    public Form1()
    {
        InitializeComponent();
        joystick = new Joystick.Joystick(this, true);
        joystick.PushChange += joystick_PushChange;
        joystick.AxeChanged += joystick_AxeChanged;
    }

    void joystick_AxeChanged(int X, int Y, int Z, int Rz)
    {
        System.Console.Write("Axis: {0}\t{1}\t{2}\t{3}\n", X, Y, Z, Rz);
    }

    void joystick_PushChange(int Push)
    {
        System.Console.Write("Push: {0}\n", Push);
    }
}


With this project, you can do lots of things, e.g. control Panzerkampf via joystick. Luckily there are events for everything (Key pressed, axe changed, ...) so you should be able to do everything with this project.

If anyone want to access multiple joysticks, you have to use the modified version of the project: JoystickMultiple. The basic principle is the same, you can use the joystick project the same way as before but you also can read single joysticks. This works like this:

Dictionary<Guid, string> foundSticks = Joystick.Joystick.GetAllJoysticks();
foreach (KeyValuePair<Guid, string> pair in foundSticks)
{
    Joystick.Joystick localStick = new Joystick.Joystick(this, false, pair.Key);
    System.Console.Write("stick: {0}\n", pair.Value);
    localStick.ButtonDown += joystick_ButtonDown;
}


joystick_ButtonDown is the following:

void joystick_ButtonDown(int ButtonNumber, Joystick.Joystick stick)
{
    System.Console.Write("{1} - Button: {0}\n", ButtonNumber, stick.Name);
}


In the modified project, every event also returns the joystick. Similar to DirectSound, the app.config has to be modyfied: <startup> has to be changed to <startup useLegacyV2RuntimeActivationPolicy="true">, otherwise the program will not start.

No comments:

Post a Comment