/// <summary> /// Updates the Joystick state by applying the given event. /// </summary> /// <param name="e">The event to apply to the state.</param> private void UpdateState(JoystickEventArgs e) { if (e.IsButtonEvent) { if (ButtonStates.ContainsKey(e.Button)) { ButtonStates[e.Button] = e.IsPressed; } else { ButtonStates.Add(e.Button, e.IsPressed); } } else { if (AxisValues.ContainsKey(e.Axis)) { AxisValues[e.Axis] = e.Value; } else { AxisValues.Add(e.Axis, e.Value); } } }
/// <summary> /// Reads from the joystick input stream and enques events to the internal event queue. /// </summary> private void JoystickInputThread() { using (FileStream inputStream = new FileStream(deviceFile, FileMode.Open)) { // Read and process in blocks of 8 bytes. byte[] buff = new byte[8]; while (running) { inputStream.Read(buff, 0, 8); JoystickEventArgs joystickEvent = DecodeJoystickEvent(buff); if (joystickEvent != null) { changes.Enqueue(joystickEvent); } } } }
/// <summary> /// Processes events received from the joystick I/O thread. /// </summary> public void ProcessEvents() { JoystickEventArgs e = null; while (!changes.IsEmpty) { if (changes.TryDequeue(out e)) { UpdateState(e); // If there are subscriptions to the event, raise the event. if (InputReceived != null) { InputReceived(this, e); } } } }