Click here to Skip to main content
11,712,241 members (66,501 online)
Click here to Skip to main content

Interfacing with a Joystick using C#

, 8 Dec 2006 348.9K 18.5K 75
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

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.

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

// 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 ( )
{
    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.

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];

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

Share

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

 
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 
I found that Axis ordering is not standard for each joystick. If one or more of your axes is showing zero but you know that it works fine in other games, Swap around these lines of code to determine which axis comes in which order. This section of code is near the bottom of Joystick.cs. It is in the UpdateStatus function.

axisA = state.X;
axisB = state.Y;
axisC = state.Z;
axisD = state.Rz;
axisE = extraAxis[0];
axisF = extraAxis[1];
GeneralJoystick connected via USB Pin
cblazer2-Jun-08 23:05
membercblazer2-Jun-08 23:05 
GeneralRe: Joystick connected via USB Pin
cblazer4-Jun-08 3:39
membercblazer4-Jun-08 3:39 
QuestionDoes anybody know how to fix the problem with .NET 3.5 and DX 10 ? Pin
Krimi24-May-08 22:15
memberKrimi24-May-08 22:15 
AnswerFix: Disable Managed Debugging Assistants Pin
Solution Alchemist16-Aug-08 11:28
memberSolution Alchemist16-Aug-08 11:28 
GeneralSlider controls Pin
ecain7-May-08 18:26
memberecain7-May-08 18:26 
GeneralRe: Slider controls Pin
ecain7-May-08 19:25
memberecain7-May-08 19:25 
GeneralThanks Pin
jibesh5-May-08 21:03
memberjibesh5-May-08 21:03 
GeneralSample cannot be debugged with .NET 3.5 and DirectX 10 Pin
signat1-May-08 8:05
membersignat1-May-08 8:05 
AnswerFix:: Disable Managed Debugging Assistants Pin
Solution Alchemist16-Aug-08 11:22
memberSolution Alchemist16-Aug-08 11:22 
GeneralRe: Fix:: Disable Managed Debugging Assistants Pin
Tboner26-Apr-09 10:00
memberTboner26-Apr-09 10:00 
Generaljoystick in background Pin
petercyyau6-Apr-08 21:28
memberpetercyyau6-Apr-08 21:28 
GeneralRe: joystick in background Pin
petercyyau6-Apr-08 22:13
memberpetercyyau6-Apr-08 22:13 
GeneralQuick question Pin
jonthejackhammer28-Mar-08 15:39
memberjonthejackhammer28-Mar-08 15:39 
GeneralRe: Quick question Pin
jonthejackhammer28-Mar-08 17:39
memberjonthejackhammer28-Mar-08 17:39 
Generalprogramming a foot pedal Pin
vikramuk13-Mar-08 23:59
membervikramuk13-Mar-08 23:59 
GeneralRe: programming a foot pedal Pin
Pragmat17-Sep-08 14:42
memberPragmat17-Sep-08 14:42 
Generalgood job!!! - just what i needed. thank you. Pin
adidimi6-Mar-08 22:56
memberadidimi6-Mar-08 22:56 
Questionjoystick connected ? Pin
Szempy6-Mar-08 12:09
memberSzempy6-Mar-08 12:09 
GeneralError Pin
Member 14826537-Feb-08 3:50
memberMember 14826537-Feb-08 3:50 
GeneralRe: Error Pin
Marauder__1-Aug-08 6:03
memberMarauder__1-Aug-08 6:03 
AnswerRe: Error Pin
Member 14826532-Aug-08 5:42
memberMember 14826532-Aug-08 5:42 
Questionmore than one joystick Pin
Member 42255266-Dec-07 2:57
memberMember 42255266-Dec-07 2:57 
GeneralThanks Pin
cool_inder25-Oct-07 9:03
membercool_inder25-Oct-07 9:03 
QuestionDemo Project Pin
Mr.Polarization18-Oct-07 7:57
memberMr.Polarization18-Oct-07 7:57 
AnswerRe: Demo Project Pin
M Harris23-Oct-07 15:18
memberM Harris23-Oct-07 15:18 
GeneralAbout button count and joystick name. Pin
zhang.hong16-Aug-07 3:16
memberzhang.hong16-Aug-07 3:16 
Questionexample game? Pin
schmiene14-Jul-07 19:34
memberschmiene14-Jul-07 19:34 
AnswerRe: example game? Pin
M Harris15-Jul-07 0:42
memberM Harris15-Jul-07 0:42 
GeneralButtons,too many buttons! Pin
kakajiao10-Jul-07 6:51
memberkakajiao10-Jul-07 6:51 
GeneralRe: Buttons,too many buttons! Pin
M Harris10-Jul-07 14:05
memberM Harris10-Jul-07 14:05 
GeneralRe: Buttons,too many buttons! Pin
kakajiao11-Jul-07 17:18
memberkakajiao11-Jul-07 17:18 
GeneralRe: Buttons,too many buttons! Pin
kakajiao11-Jul-07 17:22
memberkakajiao11-Jul-07 17:22 
GeneralRe: Buttons,too many buttons! Pin
exeCUTOR_PT24-Jan-10 16:04
memberexeCUTOR_PT24-Jan-10 16:04 
GeneralJoysticks, buttons and pedals Pin
scrlk11-Jun-07 5:47
memberscrlk11-Jun-07 5:47 
GeneralRe: Joysticks, buttons and pedals Pin
M Harris12-Jun-07 18:44
memberM Harris12-Jun-07 18:44 
GeneralThanks! Pin
mels30-Apr-07 14:21
membermels30-Apr-07 14:21 

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

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

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