Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

Interfacing with a Joystick using C#

Rate me:
Please Sign up or sign in to vote.
4.76/5 (59 votes)
8 Dec 20064 min read 585.5K   30.1K   84   118
An article on how to use a game controller/joystick with C# and Managed DirectX.
Sample Image - joystick.jpg

Introduction

When trying to find some code to use my joystick through C#, I found a sad lack of articles. There were a few posts on forums with bits and pieces of code, but no solid code on how you can use it. The scenario of a 6-axis, 20+ buttoned joystick does not seem to have occured in any C# articles before - much less on CodeProject. I intend to demonstrate how to acquire and use a full 6-axis joystick, plus all the buttons availiable.

Managed DirectX

As Managed DirectX (MDX) 2.0 is not yet released and will be included in XNA, this article uses Managed DirectX 1.1, which is fully compatible with .NET 2.0. However, you will need to change a setting within Visual Studio 2005 or a Loader Lock exception will be thrown as soon as you attempt to get a device list. The setting you need to change in VS 2005 is under the Debug menu, in Exceptions. In Managed Debugging Asssitants, uncheck "Thrown" on Loader Lock. This will allow you to debug your application. Once you have downloaded and installed the SDK, you can add a reference to Microsoft.DirectX.DirectInput to your project. To use Managed DirectX, you will have to download the DirectX Software Developers Kit. At the time of writing, the October 2006 SDK is the latest version availiable. You can download the SDK at the DirectX SDK website. It is about 500 MB, so if you are not on a fast connection, it could take some time.

Finding Your Device

To locate a joystick, a list of all game controllers that are attached to the system needs to be obtained; the DeviceList method does this. Once a list of devices has been found, the first controller in the list will be acquired. You could display a list of controllers to the user and allow for them to select the correct one if you wished.

The variable joystickDevice is a Device object declared as a private member of the class, this will be required in other methods later on.

C#
// Find all the GameControl devices that are attached.
DeviceList gameControllerList = Manager.GetDevices(DeviceClass.GameControl,
    EnumDevicesFlags.AttachedOnly);
// check that we have at least one device.
if (gameControllerList.Count > 0)
{
    // Move to the first device
    gameControllerList.MoveNext();
    DeviceInstance deviceInstance = (DeviceInstance)
        gameControllerList.Current;
    
    // create a device from this controller.
    joystickDevice = new Device(deviceInstance.InstanceGuid);
    joystickDevice.SetCooperativeLevel(this,
        CooperativeLevelFlags.Background |
        CooperativeLevelFlags.NonExclusive);
} 
    
// Tell DirectX that this is a Joystick.
joystickDevice.SetDataFormat(DeviceDataFormat.Joystick); 
// Finally, acquire the device.
joystickDevice.Acquire();

The joystickDevice variable should now be usable.

What is the Joystick Capable of?

This device can now be queried to find out what it is capable of. The DeviceCaps class is able to find out how many axes, buttons and points of view hats the joystick has.

C#
// Find the capabilities of the joystick
DeviceCaps cps = joystickDevice.Caps;
// number of Axes
Debug.WriteLine("Joystick Axis: " + cps.NumberAxes);
// number of Buttons
Debug.WriteLine("Joystick Buttons: " + cps.NumberButtons);
// number of PoV hats
Debug.WriteLine("Joystick PoV hats: " + cps.NumberPointOfViews);

These numbers will probably play an important role when writing an application implementing the joystick.

Getting Device Input

Each time the current state of the joystick is required, the Poll method needs to be called to update the joystickDevice object. Once this is done, the joystick state is updated, allowing current axis positions and button states to be found. The following private method will poll the joystick and update the state. This method updates a JoystickState object called state, which is a private field in the class.

C#
private void Poll ( )
{
    try
    {
        // poll the joystick
        joystickDevice.Poll();
        // update the joystick state field
        state = joystickDevice.CurrentJoystickState;
    }
    catch (Exception err)
    {
        // we probably lost connection to the joystick
        // was it unplugged or locked by another application?
        Debug.WriteLine(err.Message);
    }
}

The exception should probably be dealt with a little smarter, but at the moment, it doesn't matter. This method will need to be called each time we want to retrieve anything from the joystick.

Once the device has been polled for its current state, the axes positions and button state can be retrieved from the state object. The state object only has properties for four axes. The next section demonstrates retrieving the final two that are availiable if a six-axis joystick is in use. An axis' value is between 0 and 65535.

C#
int axisA = state.Rz;
int axisB = state.Rx;
int axisC = state.X;
int axisD = state.Y;

The GetButtons() method on the state object returns a byte array for each of the buttons. When the value is 128, the button has been pressed. A button is read as follows:

C#
bool buttonA = buttons[0] >= 128;

You can do this for each of your joystick's buttons. Additionally, PoV hats also show up in the buttons collection.

Finding Additional Inputs

If the joystick has additional axes that are not availiable as properties on the state object, you can use the GetSliders method to obtain an additional two axes. The GetSliders method returns an array of two ints; just like the other axis, these are values from 0 to 65535.

C#
int[] extraAxis = state.GetSlider();
int axisE = extraAxis[0];
int axisF = extraAxis[1];

Conclusion

Hopefully, this information will be useful to you and you'll be able to use your joystick without any issues. This article only covers the basics and you may wish to implement Force Feedback or PoV hats or other technologies that are availiable.

History

  • Friday, 8 December 2006 - First version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer
Australia Australia
Mark spends his spare time working on his radio control planes, helicopters and trucks. He devises new ways to make them crash faster and easier than ever before. Mark has progressed this joy of destroying nice toys into build UAV's - which can crash themselves with, or without user input.

Mark enjoys all aspects of C#, specifically windows programming and regular expressions.

Comments and Discussions

 
QuestionCode interfaces to move the joystick device in all directions in C# Pin
Aimn 20238-Apr-23 11:36
Aimn 20238-Apr-23 11:36 
QuestionTks, the code works well. Pin
Member 1079053019-Mar-21 20:11
Member 1079053019-Mar-21 20:11 
GeneralMy vote of 2 Pin
Ian Ilo2-Jun-19 17:12
Ian Ilo2-Jun-19 17:12 
Questionjoystick model and blank form Pin
Member 135625167-Dec-17 22:13
Member 135625167-Dec-17 22:13 
Questionjoystick-binsrc.zip and joystick-src.zip unzip error Pin
Ajay Batolar5-Sep-16 21:03
Ajay Batolar5-Sep-16 21:03 
Questionhow to solve error LNK 2019 in visual studio 2012 c++ ? please help me !!! Pin
Muh Rifai Anugrah14-Jan-15 11:50
Muh Rifai Anugrah14-Jan-15 11:50 
GeneralMy vote of 2 Pin
Frank R. Haugen4-Mar-14 2:55
professionalFrank R. Haugen4-Mar-14 2:55 
QuestionInterfacing with a Joystick using C# Pin
uddajay20-Feb-14 20:32
uddajay20-Feb-14 20:32 
QuestionNo Buttons and Bars in Form: Joystick using C# Pin
Member 990348926-Oct-13 4:10
Member 990348926-Oct-13 4:10 
AnswerRe: No Buttons and Bars in Form: Joystick using C# Pin
Member 135625167-Dec-17 20:04
Member 135625167-Dec-17 20:04 
QuestionException error comes : This is not a win32 application and turns out Pin
Khawaja Taimoor Tanweer2-Mar-13 9:58
Khawaja Taimoor Tanweer2-Mar-13 9:58 
AnswerRe: Exception error comes : This is not a win32 application and turns out Pin
rendi118-May-13 6:40
rendi118-May-13 6:40 
SuggestionNo need to install Microsoft DirectX SDK Pin
Uday_P24-Jan-13 2:38
Uday_P24-Jan-13 2:38 
QuestionHow to use SlimDX Pin
Khawaja Taimoor Tanweer14-Nov-12 22:03
Khawaja Taimoor Tanweer14-Nov-12 22:03 
Question2/3 Axis of joystick aint detected Pin
Member 928129313-Nov-12 22:01
Member 928129313-Nov-12 22:01 
AnswerRe: 2/3 Axis of joystick aint detected Pin
mmm374314-Nov-12 9:25
mmm374314-Nov-12 9:25 
GeneralRe: 2/3 Axis of joystick aint detected Pin
tjitra15-Jul-17 18:20
tjitra15-Jul-17 18:20 
AnswerRe: 2/3 Axis of joystick aint detected Pin
Member 102444769-Nov-13 18:04
Member 102444769-Nov-13 18:04 
Questionhow to fix OS Loader Error , plz help me Pin
OmidMohamadi15-Apr-12 1:21
OmidMohamadi15-Apr-12 1:21 
GeneralRe: how to fix OS Loader Error , plz help me Pin
User 58422378-Jul-12 6:24
User 58422378-Jul-12 6:24 
QuestionLoader Lock Problem Pin
brettaur29-Mar-12 7:32
brettaur29-Mar-12 7:32 
QuestionThanks Pin
DenizGüven23-Feb-12 4:06
DenizGüven23-Feb-12 4:06 
Questionproblem of os loader lock Pin
ritesh patel0519-Feb-12 23:00
ritesh patel0519-Feb-12 23:00 
DLL 'C:\Windows\assembly\GAC\Microsoft.DirectX\1.0.2902.0__31bf3856ad364e35\Microsoft.DirectX.dll' is attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang.

i have this problem when running code on studio 2008 can any one have solution of this
please give replay
QuestionAny Joystick Code Freezes at first Device = or DeviceList = Pin
The PC Guru17-Jan-12 17:08
The PC Guru17-Jan-12 17:08 
AnswerRe: Any Joystick Code Freezes at first Device = or DeviceList = Pin
Elad Nachmias17-Jan-12 21:57
Elad Nachmias17-Jan-12 21:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.