Click here to Skip to main content
13,458,552 members
Click here to Skip to main content
Add your own
alternative version


77 bookmarked
Posted 8 Dec 2006

Interfacing with a Joystick using C#

, 8 Dec 2006
Rate this:
Please Sign up or sign in to vote.
An article on how to use a game controller/joystick with C# and Managed DirectX.
Sample Image - joystick.jpg


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.

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

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.

// 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.

private void Poll ( )
        // poll the joystick
        // 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?

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.

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:

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.

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


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.


  • Friday, 8 December 2006 - First version


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


About the Author

M Harris
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.

You may also be interested in...


Comments and Discussions

GeneralVery poor coding Pin
BugMeNotFTW21-Jul-10 5:14
memberBugMeNotFTW21-Jul-10 5:14 
GeneralThank you and God bless you!!! Pin
t_bogdan_s9-Apr-10 11:32
membert_bogdan_s9-Apr-10 11:32 
GeneralRe: Thank you and God bless you!!! Pin
William Bello10-Mar-11 20:08
groupWilliam Bello10-Mar-11 20:08 
GeneralVariable Pressure Pin
vmor24-Feb-10 12:37
membervmor24-Feb-10 12:37 
GeneralThank You Pin
Abinash Bishoyi12-Jan-10 23:19
memberAbinash Bishoyi12-Jan-10 23:19 
GeneralThank you! (-: needed this for my team project! (VB .net) Pin
shynet16-Dec-09 9:36
membershynet16-Dec-09 9:36 
GeneralExactly what I needed. Pin
bscaer24-Nov-09 3:43
memberbscaer24-Nov-09 3:43 
QuestionProblem with Thrustmaster F430 Pin
Earlybird846-Nov-09 1:52
memberEarlybird846-Nov-09 1:52 

first of all i want to say awesome programm.

I´m working with a Thrustmaster F430 Steering wheel and want to control a rc-car via PC, that works perfect.
I woukd like to use the coolie hat button (Engine Start on the Steering wheel) for starting the car, but i the program can´t find that button on it´s own.

Now my question is had somebody a similar problem and can help me to resolve this problem?

Thanks Smile | :)

P.S. my english is not the best, but i hope you have understood me
QuestionInterfacing With Multiple Joysticks Pin
Jordon Griffiths27-Oct-09 3:02
memberJordon Griffiths27-Oct-09 3:02 
AnswerRe: Interfacing With Multiple Joysticks Pin
exeCUTOR_PT24-Jan-10 14:07
memberexeCUTOR_PT24-Jan-10 14:07 
GeneralInteracting with the POV hats Pin
driving2-Sep-09 9:50
memberdriving2-Sep-09 9:50 
GeneralRe: Interacting with the POV hats Pin
newtom25-Sep-09 1:29
membernewtom25-Sep-09 1:29 
GeneralNot working if the screen isn`t the main one Pin
skauttech23-Jul-09 23:34
memberskauttech23-Jul-09 23:34 
GeneralAwesome work Pin
cyper_21-Jul-09 13:21
membercyper_21-Jul-09 13:21 
GeneralNot quite sure how to interface with your code. Pin
Member 437529716-Jun-09 21:22
memberMember 437529716-Jun-09 21:22 
GeneralError.... Pin
yodady1429-Mar-09 16:27
memberyodady1429-Mar-09 16:27 
GeneralThanks & a quick note Pin
Mart7613-Feb-09 9:53
memberMart7613-Feb-09 9:53 
Generalplease help Pin
khaste_00712-Jan-09 11:47
memberkhaste_00712-Jan-09 11:47 
QuestionDisabling "pushed" status Pin
pmorata9-Nov-08 20:29
memberpmorata9-Nov-08 20:29 
GeneralBlank Forms Window Pin
pabsel30-Oct-08 19:47
memberpabsel30-Oct-08 19:47 
GeneralRe: Blank Forms Window Pin
mario589736629-Nov-09 11:26
membermario589736629-Nov-09 11:26 
GeneralNew joystick support Pin
tlhintoq25-Jul-08 1:27
membertlhintoq25-Jul-08 1:27 
AnswerRe: New joystick support Pin
TimJoseph8-Oct-08 16:08
memberTimJoseph8-Oct-08 16:08 
GeneralRe: New joystick support Pin
tlhintoq8-Oct-08 16:16
membertlhintoq8-Oct-08 16:16 
GeneralJoystick Axis Problem Pin
cvoss4218-Jun-08 19:52
membercvoss4218-Jun-08 19:52 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180323.1 | Last Updated 8 Dec 2006
Article Copyright 2006 by M Harris
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid