Mengakses Joystick USB Visual C#

Proyek yang akan dibuat menggunakan Visual C# Express 2010 dengan library dari SlimDX yang mencoba mengakses USB Joystick di PC.

JoyStick8

Berikut adalah sample yang saya dapat dari  file sample dari SlimDX Samples (Sept 2011) dengan .NET Framework 2 karena itu saya edit kembali dengan .NET Framework 4.

Download page: slimdx.org/download.php

Developer SDK: code.google.com/p/slimdx/downloads/detail?name=SlimDX%20SDK%20%28January%202012%29.msi

Download page: slimdx.org/download_sep11.php

Developer SDK: slimdx.googlecode.com/files/SlimDX%20SDK%20%28September%202011%29.msi

Buatlah NewProject WindowsForm pada aplikasi Visual C# dan beri nama Joystick.

JoyStick1

JoyStick2

Control Property Value Events Value

MainForm

FormBorderStyle FixedSingle

FormClosed

MainForm_FormClosed

AutoSizeMode GrowOnly
AutoSize

FALSE

Text “SlimDX – Joystick Sample”
groupBox_JoystickState Text “Joystick State”
label_Message Text “This sample polls the joystick for data.When in immediate mode, joystick data is lost
between updates.”
   
createDeviceButton Text “Create Device” Click createDeviceButton_Click
exitButton Text “Exit” Click exitButton_Click
label_XAxis Text “X Axis:”
label_YAxis Text “Y Axis:”
label_ZAxis Text “Z Axis:”
label_XRotation Text “X Rotation:”    
label_YRotation Text “Y Rotation:”
label_ZRotation Text “Z Rotation:”
label_Buttons Text “Button(s):”
label_X Text “0”
label_Y Text “0”
label_Z Text “0”    
label_XRot Text “0”
label_YRot Text “0”
label_ZRot Text “0”
label_ButtonList Text “”
label_Slider0 Text “Slider 0:”
label_Slider1 Text “Slider 1:”    
label_POV0 Text “POV 0:”
label_POV1 Text “POV 1:”
label_POV2 Text “POV 2:”
label_POV3 Text “POV 3:”
label_S0 Text “0”
label_S1 Text “0”
label_P0 Text “0”
label_P1 Text “0”
label_P2 Text “0”
label_P3 Text “0”
timer Tick timer_Tick

Properties bisa dilihat di jendela Properties. Begitu juga Events.

JoyStick3

JoyStick4

Setelah membuat disain GUI-nya, sekarang kita masukan library SlimDX dengan cara klik kanan di References yang terdapat pada jendela Solution Explorer lalu klik Add Reference…

JoyStick5

Lalu browse library SlimDX.dll

JoyStick6

File SlimDX.dll ada pada directory SlimDX\SlimDX SDK (January 2012)\Bin\net40\x86 atau pilih sesuai spesifikasi yang digunakan.

Setelah itu klik kanan pada MainForm.cs lalu pilih View Code untuk mengedit kode. JoyStick7

Berikut kode lengkapnya.

using System;
using System.Globalization;
using System.Windows.Forms;
using SlimDX;
using SlimDX.DirectInput;
using System.Collections.Generic;

namespace JoystickTest
{
    public partial class MainForm : Form
    {
        Joystick joystick;

        JoystickState state = new JoystickState();
        int numPOVs;
        int SliderCount;

        void CreateDevice()
        {
            // make sure that DirectInput has been initialized
            DirectInput dinput = new DirectInput();

            // search for devices
            foreach (DeviceInstance device in dinput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly))
            {
                // create the device
                try
                {
                    joystick = new Joystick(dinput, device.InstanceGuid);
                    joystick.SetCooperativeLevel(this, CooperativeLevel.Exclusive | CooperativeLevel.Foreground);
                    break;
                }
                catch (DirectInputException)
                {
                }
            }

            if (joystick == null)
            {
                MessageBox.Show("There are no joysticks attached to the system.");
                return;
            }

            foreach (DeviceObjectInstance deviceObject in joystick.GetObjects())
            {
                if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)
                    joystick.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-1000, 1000);

                UpdateControl(deviceObject);
            }

            // acquire the device
            joystick.Acquire();

            // set the timer to go off 12 times a second to read input
            // NOTE: Normally applications would read this much faster.
            // This rate is for demonstration purposes only.
            timer.Interval = 1000 / 12;
            timer.Start();
        }

        void ReadImmediateData()
        {
            if (joystick.Acquire().IsFailure)
                return;

            if (joystick.Poll().IsFailure)
                return;

            state = joystick.GetCurrentState();
            if (Result.Last.IsFailure)
                return;

            UpdateUI();
        }

        void ReleaseDevice()
        {
            timer.Stop();

            if (joystick != null)
            {
                joystick.Unacquire();
                joystick.Dispose();
            }
            joystick = null;
        }

        #region Boilerplate

        public MainForm()
        {
            InitializeComponent();
            UpdateUI();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            ReadImmediateData();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            ReleaseDevice();
            Close();
        }

        void UpdateUI()
        {
            if (joystick == null)
                createDeviceButton.Text = "Create Device";
            else
                createDeviceButton.Text = "Release Device";

            string strText = null;

            label_X.Text = state.X.ToString(CultureInfo.CurrentCulture);
            label_Y.Text = state.Y.ToString(CultureInfo.CurrentCulture);
            label_Z.Text = state.Z.ToString(CultureInfo.CurrentCulture);

            label_XRot.Text = state.RotationX.ToString(CultureInfo.CurrentCulture);
            label_YRot.Text = state.RotationY.ToString(CultureInfo.CurrentCulture);
            label_ZRot.Text = state.RotationZ.ToString(CultureInfo.CurrentCulture);

            int[] slider = state.GetSliders();

            label_S0.Text = slider[0].ToString(CultureInfo.CurrentCulture);
            label_S1.Text = slider[1].ToString(CultureInfo.CurrentCulture);

            int[] pov = state.GetPointOfViewControllers();

            label_P0.Text = pov[0].ToString(CultureInfo.CurrentCulture);
            label_P1.Text = pov[1].ToString(CultureInfo.CurrentCulture);
            label_P2.Text = pov[2].ToString(CultureInfo.CurrentCulture);
            label_P3.Text = pov[3].ToString(CultureInfo.CurrentCulture);

            bool[] buttons = state.GetButtons();

            for (int b = 0; b < buttons.Length; b++)
            {
                if (buttons[b])
                    strText += b.ToString("00 ", CultureInfo.CurrentCulture);
            }
            label_ButtonList.Text = strText;
        }

        void UpdateControl(DeviceObjectInstance d)
        {
            if (ObjectGuid.XAxis == d.ObjectTypeGuid)
            {
                label_XAxis.Enabled = true;
                label_X.Enabled = true;
            }
            if (ObjectGuid.YAxis == d.ObjectTypeGuid)
            {
                label_YAxis.Enabled = true;
                label_Y.Enabled = true;
            }
            if (ObjectGuid.ZAxis == d.ObjectTypeGuid)
            {
                label_ZAxis.Enabled = true;
                label_Z.Enabled = true;
            }
            if (ObjectGuid.RotationalXAxis == d.ObjectTypeGuid)
            {
                label_XRotation.Enabled = true;
                label_XRot.Enabled = true;
            }
            if (ObjectGuid.RotationalYAxis == d.ObjectTypeGuid)
            {
                label_YRotation.Enabled = true;
                label_YRot.Enabled = true;
            }
            if (ObjectGuid.RotationalZAxis == d.ObjectTypeGuid)
            {
                label_ZRotation.Enabled = true;
                label_ZRot.Enabled = true;
            }

            if (ObjectGuid.Slider == d.ObjectTypeGuid)
            {
                switch (SliderCount++)
                {
                    case 0:
                        label_Slider0.Enabled = true;
                        label_S0.Enabled = true;
                        break;

                    case 1:
                        label_Slider1.Enabled = true;
                        label_S1.Enabled = true;
                        break;
                }
            }

            if (ObjectGuid.PovController == d.ObjectTypeGuid)
            {
                switch (numPOVs++)
                {
                    case 0:
                        label_POV0.Enabled = true;
                        label_P0.Enabled = true;
                        break;

                    case 1:
                        label_POV1.Enabled = true;
                        label_P1.Enabled = true;
                        break;

                    case 2:
                        label_POV2.Enabled = true;
                        label_P2.Enabled = true;
                        break;

                    case 3:
                        label_POV3.Enabled = true;
                        label_P3.Enabled = true;
                        break;
                }
            }
        }

        private void createDeviceButton_Click(object sender, EventArgs e)
        {
            if (joystick == null)
                CreateDevice();
            else
                ReleaseDevice();
            UpdateUI();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            ReleaseDevice();
        }

        #endregion
    }
}

2 Responses to Mengakses Joystick USB Visual C#

  1. Tria says:

    Saya ingin bertanya, apakah SLIM DX ini bisa digunakan dengan bahasa pemrograman C++ dan menggunakan MFC.. Terimakasih sebelumnya🙂

    • wangready says:

      sya gk tau gan, saya pakenya c#. tp kalo menurut webnya slimdx.org : “SlimDX is a free open source framework that enables developers to easily build DirectX applications using any .NET language”. jd sepertinya bisa saja…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s