Tambahkan paket NuGet SharpDX.DirectInput
using System; using System.Threading; using SharpDX.DirectInput; namespace PanelRosita { public enum ButtonState : int { Idle = -1, Released = 0, Pressed = 128 } public class JoystickThread { public Thread thr; public bool conditionToExitReceived = false; public bool isJoystickDetected = false; public JoystickThread(string name) { // detecting joystick // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; var devInstance = new DeviceInstance(); foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; devInstance = deviceInstance; } // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; devInstance = deviceInstance; } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No joystick/Gamepad found."); conditionToExitReceived = true; throw new Exception("No joystick/Gamepad found."); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); thr = new Thread(() => RunThread(joystick) ); thr.Name = name; thr.Start(); isJoystickDetected = true; } // Enetring point for thread void RunThread(Joystick joystick) { // Query all suported ForceFeedback effects Console.WriteLine("Effect:"); var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) Console.WriteLine("Effect available {0}", effectInfo.Name); // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); try { while (true) { if (conditionToExitReceived) // what im waiting for... { Console.WriteLine("Thread is finished"); break; } Thread.Sleep(10); // wait 1 second for something to happen. doStuff(ref joystick); } //perform cleanup if there is any... } catch (ThreadAbortException ex) { Console.WriteLine("Thread " + thr.Name + " is aborted and the code is " + ex.ExceptionState); } } private void doStuff(ref Joystick joystick) { try { joystick.Poll(); var datas = joystick.GetBufferedData(); foreach (var state in datas) { JoystickButtonPressedEventArgs args = new JoystickButtonPressedEventArgs(); JoystickButtonPOVEventArgs povargs = new JoystickButtonPOVEventArgs(); args.Value = (ButtonState)state.Value; args.ButtonOffset = state.RawOffset; args.TimeStamp = DateTime.Now; povargs.Value = state.Value; if (state.Offset == JoystickOffset.Buttons0) { OnJoystickButton0(args); } if (state.Offset == JoystickOffset.PointOfViewControllers0) { OnJoystickPointOfViewControllers0(povargs); } if (state.Offset != JoystickOffset.X && state.Offset != JoystickOffset.Y && state.Offset != JoystickOffset.RotationZ) { Console.WriteLine("Joystick: " + state); } } } catch (Exception ee) { OnJoystickDisconnected(ee.Message); conditionToExitReceived = true; Console.WriteLine("Joystick: " + ee); isJoystickDetected = false; } } public class JoystickButtonPressedEventArgs : EventArgs { public ButtonState Value { get; set; } public int ButtonOffset { get; set; } public DateTime TimeStamp { get; set; } } public class JoystickButtonPOVEventArgs : EventArgs { public int Value { get; set; } public int ButtonOffset { get; set; } public DateTime TimeStamp { get; set; } } public event EventHandler<String> OnDisconnected0; protected virtual void OnJoystickDisconnected(String e) { EventHandler<String> handler = OnDisconnected0; if (handler != null) { handler(this, e); } } public event EventHandler<JoystickButtonPressedEventArgs> OnButton0; protected virtual void OnJoystickButton0(JoystickButtonPressedEventArgs e) { EventHandler<JoystickButtonPressedEventArgs> handler = OnButton0; if (handler != null) { handler(this, e); } } public event EventHandler<JoystickButtonPOVEventArgs> OnPointOfViewControllers0; protected virtual void OnJoystickPointOfViewControllers0(JoystickButtonPOVEventArgs e) { EventHandler<JoystickButtonPOVEventArgs> handler = OnPointOfViewControllers0; if (handler != null) { handler(this, e); } } } }
Penggunaan
JoystickThread jt; private void Form1_Load(object sender, EventArgs e) { ConnectingToJoystick(FindingJoystick()); } private void ErrorBox(string v) { MessageBox.Show(v,Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } private void ConnectingToJoystick(bool joystickDetected) { if (joystickDetected) { try { jt = new JoystickThread("JoyStick"); if (jt.isJoystickDetected) { //add all event here jt.OnButton0 += Jt_OnButton0; jt.OnDisconnected0 += Jt_OnDisconnected0; jt.OnPointOfViewControllers0 += Jt_OnPointOfViewControllers0; jt.isJoystickDetected = true; } else { ErrorBox("Joystick tidak terdeteksi atau tidak kompatibel"); } } catch (Exception ee) { ErrorBox("Joystick:" + ee.Message); } } } private static bool FindingJoystick() { Boolean joystickDetected = false; // Initialize DirectInput var directInput = new DirectInput(); while (!joystickDetected) { var devInstance = new DeviceInstance(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; devInstance = deviceInstance; } // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; devInstance = deviceInstance; } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No joystick/Gamepad found."); DialogResult rst = MessageBox.Show("Joystick tidak ditemukan atau tidak terhubung. Hubungkan joystick dan klik RETRY, atau klik CANCEL untuk tidak menggunakan joystick.", Application.ProductName, MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning); if (rst == DialogResult.Cancel) { return joystickDetected; } } else { joystickDetected = true; } } return joystickDetected; } private void Jt_OnDisconnected0(object sender, string e) { //stop robot //Finding joystick DialogResult rst = MessageBox.Show("No Joystick found. Please Connect the joystick.", Application.ProductName, MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning); if (rst == DialogResult.Retry) { ConnectingToJoystick(FindingJoystick()); } } private void Jt_OnPointOfViewControllers0(object sender, JoystickThread.JoystickButtonPOVEventArgs e) { MessageBox.Show("POV value: "+e.Value.ToString()); } private void Jt_OnButton0(object sender, JoystickThread.JoystickButtonPressedEventArgs e) { String state = ""; if (e.Value == ButtonState.Pressed) state = "Pencet"; else state = "Lepas"; //Invoke state to button1 //button1.Invoke(new Action(() => button1.Text = state)); } //Add event on FormClosing to release object private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (jt != null) { //force to abort //jt.thr.Abort("aborted from Main"); //ask thread to exit polling jt.conditionToExitReceived = true; // Waiting for a thread to terminate. jt.thr.Join(); Console.WriteLine(jt.thr.Name + " is terminate"); } }