//for converting a struct to byte array public static byte[] getBytesSFJ(SetFeatureJoy sfj, int size) { var arr = new byte[size]; var ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(sfj, ptr, false); Marshal.Copy(ptr, arr, 0, size); Marshal.FreeHGlobal(ptr); return(arr); }
//here we send data to the joystick void Send_Data_To_Joystick() { var JoyData = new SetFeatureJoy(); JoyData.ReportID = 1; JoyData.CommandCode = 2; JoyData.X = (ushort)slX.Value; JoyData.Y = (ushort)slY.Value; JoyData.Z = (ushort)slZ.Value; JoyData.rX = (ushort)slrX.Value; JoyData.rY = (ushort)slrY.Value; JoyData.rZ = (ushort)slrZ.Value; JoyData.slider = (ushort)slSlider.Value; JoyData.wheel = (ushort)slWheel.Value; JoyData.dial = (ushort)slDial.Value; JoyData.hat = (byte)slHat.Value; //non-hat buttons are represented as a bit array of 16 bytes, 1 bit per button. //we could have used a byte array here, but for simplicity we instead just declared 16 byte variables. //each button is represented by 1 bit. The bit is 1 if pressed, 0 if not pressed. //in this example, we'll only show the first 8 buttons and also button 128. JoyData.btn0 = 0; if (cb0.IsChecked == true) { JoyData.btn0 = (byte)(JoyData.btn0 | (1 << 0)); } if (cb1.IsChecked == true) { JoyData.btn0 = (byte)(JoyData.btn0 | (1 << 1)); } if (cb2.IsChecked == true) { JoyData.btn0 = (byte)(JoyData.btn0 | (1 << 2)); } if (cb3.IsChecked == true) { JoyData.btn0 = (byte)(JoyData.btn0 | (1 << 3)); } if (cb4.IsChecked == true) { JoyData.btn0 = (byte)(JoyData.btn0 | (1 << 4)); } if (cb5.IsChecked == true) { JoyData.btn0 = (byte)(JoyData.btn0 | (1 << 5)); } if (cb6.IsChecked == true) { JoyData.btn0 = (byte)(JoyData.btn0 | (1 << 6)); } if (cb7.IsChecked == true) { JoyData.btn0 = (byte)(JoyData.btn0 | (1 << 7)); } JoyData.btn1 = 0; if (cb8.IsChecked == true) { JoyData.btn1 = (byte)(JoyData.btn1 | (1 << 0)); } JoyData.btn15 = 0; if (cb128.IsChecked == true) { JoyData.btn15 = (byte)(JoyData.btn15 | (1 << 0)); } //convert struct to buffer var buf = getBytesSFJ(JoyData, Marshal.SizeOf(JoyData)); //send filled buffer to driver HID.SendData(buf, (uint)Marshal.SizeOf(JoyData)); }