{"id":22551327,"url":"https://github.com/joelumbley/xinput","last_synced_at":"2026-02-13T15:33:38.354Z","repository":{"id":157477130,"uuid":"633503981","full_name":"JoeLumbley/XInput","owner":"JoeLumbley","description":"Use Xbox controllers in your games.","archived":false,"fork":false,"pushed_at":"2025-02-04T07:43:53.000Z","size":396,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-05-29T17:18:18.266Z","etag":null,"topics":["bumper","buttons","computer-science","controller","desktop-application","dpad","game-controller","game-development","k-12-education","rumble","thumbstick","trigger","vb-net","vibration","windows-desktop-app","xbox","xbox-controller","xinput","xinputgetstate"],"latest_commit_sha":null,"homepage":"","language":"Visual Basic .NET","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JoeLumbley.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-04-27T16:35:21.000Z","updated_at":"2025-02-04T07:43:56.000Z","dependencies_parsed_at":null,"dependency_job_id":"8723f904-ad99-4c1d-8634-0b008577f373","html_url":"https://github.com/JoeLumbley/XInput","commit_stats":{"total_commits":49,"total_committers":2,"mean_commits":24.5,"dds":"0.10204081632653061","last_synced_commit":"b0d072e2f8227d02489ab68c4707044211a5d6c5"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/JoeLumbley/XInput","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JoeLumbley%2FXInput","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JoeLumbley%2FXInput/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JoeLumbley%2FXInput/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JoeLumbley%2FXInput/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JoeLumbley","download_url":"https://codeload.github.com/JoeLumbley/XInput/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JoeLumbley%2FXInput/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273409560,"owners_count":25100446,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-03T02:00:09.631Z","response_time":76,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bumper","buttons","computer-science","controller","desktop-application","dpad","game-controller","game-development","k-12-education","rumble","thumbstick","trigger","vb-net","vibration","windows-desktop-app","xbox","xbox-controller","xinput","xinputgetstate"],"created_at":"2024-12-07T17:12:12.994Z","updated_at":"2026-02-13T15:33:38.278Z","avatar_url":"https://github.com/JoeLumbley.png","language":"Visual Basic .NET","funding_links":[],"categories":[],"sub_categories":[],"readme":"# XInput 🎮\n\n Welcome to XInput, your go-to solution for integrating Xbox controller support into your applications! This feature-rich application showcases the seamless integration of Xbox controllers, complete with vibration effects and real-time controller state monitoring. \n\n\n![013](https://github.com/user-attachments/assets/f65a0636-577b-4d96-bd0f-6dd82db5357c)\n\n\nWith a clean and well-commented codebase, this project serves as an invaluable resource for developers looking to harness the power of XInput in their Windows applications. Whether you're a seasoned developer or just getting started, the XInput app provides a solid foundation for building immersive gaming experiences and beyond.\n\n\n\n\n\n\n\n\n\n\n---\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Code Walkthrough\n\nWelcome to the XInput project in this walkthrough, we will go through the code line by line to understand how it works. This code is designed to integrate Xbox controller support into applications, allowing developers to interact with Xbox controllers seamlessly. Let's dive in!\n\n## Imports\n\n```vb\nImports System.Runtime.InteropServices\n```\n- **Imports System.Runtime.InteropServices**: This line imports the `System.Runtime.InteropServices` namespace, which provides functionality for interacting with unmanaged code. This is crucial for calling functions from the XInput library, which is used to communicate with Xbox controllers.\n\n[Index](#index)\n\n---\n\n## XboxControllers Structure\n\n```vb\nPublic Structure XboxControllers\n```\n- **Public Structure XboxControllers**: This defines a public structure named `XboxControllers`. A structure is a value type that can hold data members and methods related to Xbox controller input.\n\n[Index](#index)\n\n---\n\n### DllImport for XInputGetState\n\n```vb\n\u003cDllImport(\"XInput1_4.dll\")\u003e\nPrivate Shared Function XInputGetState(dwUserIndex As Integer,\n                                 ByRef pState As XINPUT_STATE) As Integer\nEnd Function\n```\n- **\u003cDllImport(\"XInput1_4.dll\")\u003e**: This attribute allows the function `XInputGetState` to be called from the XInput DLL, which is necessary for getting the current state of the Xbox controller.\n- **Private Shared Function XInputGetState**: This function retrieves the current state of the specified Xbox controller.\n  - **dwUserIndex**: An integer that represents the index of the controller (0 for the first, 1 for the second, etc.).\n  - **ByRef pState As XINPUT_STATE**: A reference to an `XINPUT_STATE` structure that will be filled with the controller's state. The function returns an integer indicating success or failure.\n\n[Index](#index)\n\n---\n\n### XINPUT_STATE Structure\n\n```vb\n\u003cStructLayout(LayoutKind.Explicit)\u003e\nPublic Structure XINPUT_STATE\n    \u003cFieldOffset(0)\u003e\n    Public dwPacketNumber As UInteger\n    \u003cFieldOffset(4)\u003e\n    Public Gamepad As XINPUT_GAMEPAD\nEnd Structure\n```\n- **\u003cStructLayout(LayoutKind.Explicit)\u003e**: This attribute specifies that the layout of the structure is defined explicitly, allowing for precise control over the memory layout.\n- **Public Structure XINPUT_STATE**: This structure holds the state of the controller.\n  - **dwPacketNumber**: An unsigned 32-bit integer range 0 through 4,294,967,295 that helps track the state changes.\n  - **Gamepad**: An instance of the `XINPUT_GAMEPAD` structure, which contains the button and thumbstick states.\n\n[Index](#index)\n\n---\n\n### XINPUT_GAMEPAD Structure\n\n```vb\n\u003cStructLayout(LayoutKind.Sequential)\u003e\nPublic Structure XINPUT_GAMEPAD\n    Public wButtons As UShort ' Unsigned 16-bit (2-byte) integer range 0 through 65,535.\n    Public bLeftTrigger As Byte ' Unsigned 8-bit (1-byte) integer range 0 through 255.\n    Public bRightTrigger As Byte\n    Public sThumbLX As Short ' Signed 16-bit (2-byte) integer range -32,768 through 32,767.\n    Public sThumbLY As Short\n    Public sThumbRX As Short\n    Public sThumbRY As Short\nEnd Structure\n```\n- **\u003cStructLayout(LayoutKind.Sequential)\u003e**: This attribute specifies that the fields of the structure should be laid out in the order they are defined.\n- **Public Structure XINPUT_GAMEPAD**: This structure contains the states of the gamepad buttons and thumbsticks.\n  - **wButtons**: Stores the state of the buttons. Each button has a unique bit value.\n  - **bLeftTrigger** and **bRightTrigger**: Store the values of the left and right triggers, respectively.\n  - **sThumbLX**, **sThumbLY**, **sThumbRX**, **sThumbRY**: Store the positions of the thumbsticks along the X and Y axes.\n\n[Index](#index)\n\n---\n\n### State Variable\n\n```vb\nPrivate State As XINPUT_STATE\n```\n- **Private State As XINPUT_STATE**: This variable will hold the current state of the Xbox controller.\n\n[Index](#index)\n\n---\n\n### Button Enumeration\n\n```vb\nPrivate Enum Button\n    DPadUp = 1\n    DPadDown = 2\n    DPadLeft = 4\n    DPadRight = 8\n    Start = 16\n    Back = 32\n    LeftStick = 64\n    RightStick = 128\n    LeftBumper = 256\n    RightBumper = 512\n    A = 4096\n    B = 8192\n    X = 16384\n    Y = 32768\nEnd Enum\n```\n- **Private Enum Button**: This enumeration defines constants for each button on the Xbox controller. Each button is assigned a unique bit value, allowing for easy state checking using bitwise operations.\n\n[Index](#index)\n\n---\n\n### Neutral Zone Constants\n\n```vb\nPrivate Const NeutralStart As Short = -16384 '-16,384 = -32,768 / 2\nPrivate Const NeutralEnd As Short = 16384 '16,383.5 = 32,767 / 2\n```\n- **Private Const NeutralStart**: This constant defines the starting point of the thumbstick neutral zone.\n- **Private Const NeutralEnd**: This constant defines the endpoint of the thumbstick neutral zone. The thumbstick must move beyond these points to register as active.\n\n[The Neutral Zone](#the-neutral-zone)\n\n\n[Index](#index)\n\n---\n\n### Trigger Threshold Constant\n\n```vb\nPrivate Const TriggerThreshold As Byte = 64 '64 = 256 / 4\n```\n- **Private Const TriggerThreshold**: This constant sets the minimum value for the triggers to be considered pressed.\n\n\n[The Trigger Threshold](#the-trigger-threshold)\n\n\n[Index](#index)\n\n---\n\n### Connected Controllers Array\n\n```vb\nPublic Connected() As Boolean\n```\n- **Public Connected() As Boolean**: This array keeps track of whether up to four controllers are connected.\n\n[Index](#index)\n\n---\n\n### Other Variables\n\n```vb\nPrivate ConnectionStart As Date\nPublic Buttons() As UShort\nPublic LeftThumbstickXaxisNeutral() As Boolean\nPublic LeftThumbstickYaxisNeutral() As Boolean\nPublic RightThumbstickXaxisNeutral() As Boolean\nPublic RightThumbstickYaxisNeutral() As Boolean\nPublic DPadNeutral() As Boolean\nPublic LetterButtonsNeutral() As Boolean\n```\n- These variables are used to store various states of the controllers, including button states, thumbstick positions, and whether the D-Pad and letter buttons are in a neutral position.\n\n[Index](#index)\n\n---\n\n### Initialize Method\n\n```vb\nPublic Sub Initialize()\n```\n- **Public Sub Initialize()**: This method initializes the Xbox controller structure and its properties.\n\n\n\n#### Inside the Initialize Method\n\n```vb\nConnected = New Boolean(0 To 3) {}\n```\n- Initializes the `Connected` array to indicate whether controllers are connected.\n\n```vb\nConnectionStart = DateTime.Now\n```\n- Records the current date and time when initialization starts.\n\n```vb\nButtons = New UShort(0 To 3) {}\n```\n- Initializes the `Buttons` array to store the state of the controller buttons.\n\n```vb\nLeftThumbstickXaxisNeutral = New Boolean(0 To 3) {}\nLeftThumbstickYaxisNeutral = New Boolean(0 To 3) {}\nRightThumbstickXaxisNeutral = New Boolean(0 To 3) {}\nRightThumbstickYaxisNeutral = New Boolean(0 To 3) {}\n```\n- Initializes arrays to check if thumbstick axes are in the neutral position.\n\n```vb\nDPadNeutral = New Boolean(0 To 3) {}\nLetterButtonsNeutral = New Boolean(0 To 3) {}\n```\n- Initializes arrays to check if the D-Pad and letter buttons are in the neutral position.\n\n```vb\nFor i As Integer = 0 To 3\n    LeftThumbstickXaxisNeutral(i) = True\n    LeftThumbstickYaxisNeutral(i) = True\n    RightThumbstickXaxisNeutral(i) = True\n    RightThumbstickYaxisNeutral(i) = True\n    DPadNeutral(i) = True\n    LetterButtonsNeutral(i) = True\nNext\n```\n- This loop sets all thumbstick axes and button states to neutral for all controllers.\n\n```vb\nTimeToVibe = 1000 'ms\n```\n- Sets the default vibration time to 1000 milliseconds (1 second).\n\n```vb\nTestInitialization()\n```\n- Calls the `TestInitialization` method to verify that everything is set up correctly.\n\n[Index](#index)\n\n---\n\n### Update Method\n\n```vb\nPublic Sub Update()\n```\n- **Public Sub Update()**: This method is called repeatedly to check for updates in the controller state.\n\n\n#### Inside the Update Method\n\n```vb\nDim ElapsedTime As TimeSpan = Now - ConnectionStart\n```\n- Calculates the elapsed time since the connection started.\n\n```vb\nIf ElapsedTime.TotalSeconds \u003e= 1 Then\n    For ControllerNumber As Integer = 0 To 3\n        Connected(ControllerNumber) = IsConnected(ControllerNumber)\n    Next\n    ConnectionStart = DateTime.Now\nEnd If\n```\n- Every second, it checks if the controllers are still connected and updates the `Connected` array accordingly.\n\n```vb\nFor ControllerNumber As Integer = 0 To 3\n    If Connected(ControllerNumber) Then\n        UpdateState(ControllerNumber)\n    End If\nNext\n```\n- Loops through each controller and updates its state if it is connected.\n\n```vb\nUpdateVibrateTimers()\n```\n- Calls the method to update the vibration timers for the controllers.\n\n[Index](#index)\n\n---\n\n### UpdateState Method\n\n```vb\nPublic Sub UpdateState(controllerNumber As Integer)\n```\n- **Public Sub UpdateState(controllerNumber As Integer)**: This method retrieves and updates the state of a specific controller.\n\n\n#### Inside the UpdateState Method\n\n```vb\nTry\n    XInputGetState(controllerNumber, State)\n    UpdateButtons(controllerNumber)\n    UpdateThumbsticks(controllerNumber)\n    UpdateTriggers(controllerNumber)\nCatch ex As Exception\n    Debug.Print($\"Error getting XInput state: {controllerNumber} | {ex.Message}\")\nEnd Try\n```\n- Tries to get the state of the specified controller and update its buttons, thumbsticks, and triggers. If an error occurs, it prints the error message to the debug console.\n\n[Index](#index)\n\n---\n\n### UpdateButtons Method\n\n```vb\nPrivate Sub UpdateButtons(CID As Integer)\n```\n- **Private Sub UpdateButtons(CID As Integer)**: This method updates the state of the buttons for the specified controller.\n\n\n#### Inside the UpdateButtons Method\n\n```vb\nUpdateDPadButtons(CID)\nUpdateLetterButtons(CID)\nUpdateBumperButtons(CID)\nUpdateStickButtons(CID)\nUpdateStartBackButtons(CID)\nUpdateDPadNeutral(CID)\nUpdateLetterButtonsNeutral(CID)\nButtons(CID) = State.Gamepad.wButtons\n```\n- Calls various methods to update the states of the D-Pad, letter buttons, bumpers, stick buttons, and start/back buttons. It also updates the `Buttons` array with the current state of the buttons.\n\n[Index](#index)\n\n---\n\n### UpdateThumbsticks and UpdateTriggers Methods\n\n```vb\nPrivate Sub UpdateThumbsticks(controllerNumber As Integer)\n    UpdateLeftThumbstick(controllerNumber)\n    UpdateRightThumbstick(controllerNumber)\nEnd Sub\n\nPrivate Sub UpdateTriggers(controllerNumber As Integer)\n    UpdateLeftTrigger(controllerNumber)\n    UpdateRightTrigger(controllerNumber)\nEnd Sub\n```\n- These methods call their respective update methods for the left and right thumbsticks and triggers.\n\n[Index](#index)\n\n---\n\n### UpdateDPadButtons Method\n\n```vb\nPrivate Sub UpdateDPadButtons(CID As Integer)\n    DPadUp(CID) = (State.Gamepad.wButtons And Button.DPadUp) \u003c\u003e 0\n    DPadDown(CID) = (State.Gamepad.wButtons And Button.DPadDown) \u003c\u003e 0\n    DPadLeft(CID) = (State.Gamepad.wButtons And Button.DPadLeft) \u003c\u003e 0\n    DPadRight(CID) = (State.Gamepad.wButtons And Button.DPadRight) \u003c\u003e 0\nEnd Sub\n```\n- This method checks the current state of the D-Pad buttons and updates the corresponding boolean arrays.\n\n[Index](#index)\n\n---\n\n### UpdateThumbstick Methods\n\n```vb\nPrivate Sub UpdateLeftThumbstick(ControllerNumber As Integer)\n    UpdateLeftThumbstickXaxis(ControllerNumber)\n    UpdateLeftThumbstickYaxis(ControllerNumber)\nEnd Sub\n\nPrivate Sub UpdateRightThumbstick(ControllerNumber As Integer)\n    UpdateRightThumbstickXaxis(ControllerNumber)\n    UpdateRightThumbstickYaxis(ControllerNumber)\nEnd Sub\n```\n- These methods call the respective methods to update the X and Y axes of the left and right thumbsticks.\n\n[Index](#index)\n\n---\n\n### UpdateTrigger Methods\n\n```vb\nPrivate Sub UpdateLeftTrigger(ControllerNumber As Integer)\n    If State.Gamepad.bLeftTrigger \u003e TriggerThreshold Then\n        LeftTrigger(ControllerNumber) = True\n    Else\n        LeftTrigger(ControllerNumber) = False\n    End If\nEnd Sub\n\nPrivate Sub UpdateRightTrigger(ControllerNumber As Integer)\n    If State.Gamepad.bRightTrigger \u003e TriggerThreshold Then\n        RightTrigger(ControllerNumber) = True\n    Else\n        RightTrigger(ControllerNumber) = False\n    End If\nEnd Sub\n```\n- These methods check the state of the left and right triggers against the threshold and update their respective boolean arrays.\n\n[Index](#index)\n\n---\n\n### UpdateDPadNeutral Method\n\n```vb\nPrivate Sub UpdateDPadNeutral(controllerNumber As Integer)\n    If DPadDown(controllerNumber) Or DPadLeft(controllerNumber) Or DPadRight(controllerNumber) Or DPadUp(controllerNumber) Then\n        DPadNeutral(controllerNumber) = False\n    Else\n        DPadNeutral(controllerNumber) = True\n    End If\nEnd Sub\n```\n- This method checks if any D-Pad buttons are pressed and updates the neutral state accordingly.\n\n[Index](#index)\n\n---\n\n### IsConnected Method\n\n```vb\nPublic Function IsConnected(controllerNumber As Integer) As Boolean\n```\n- **Public Function IsConnected(controllerNumber As Integer) As Boolean**: This method checks if a specific controller is connected.\n\n\n#### Inside the IsConnected Method\n\n```vb\nTry\n    Return XInputGetState(controllerNumber, State) = 0\nCatch ex As Exception\n    Debug.Print($\"Error getting XInput state: {controllerNumber} | {ex.Message}\")\n    Return False\nEnd Try\n```\n- It attempts to get the state of the specified controller. If successful (returns 0), the controller is connected. If an error occurs, it prints the error message and returns `False`.\n\n[Index](#index)\n\n---\n\n### TestInitialization Method\n\n```vb\nPublic Sub TestInitialization()\n```\n- **Public Sub TestInitialization()**: This method verifies that the initialization of the controllers was successful.\n\n\n#### Inside the TestInitialization Method\n\n```vb\nDebug.Assert(Not ConnectionStart = Nothing, $\"Connection Start should not be Nothing.\")\nDebug.Assert(Buttons IsNot Nothing, $\"Buttons should not be Nothing.\")\nDebug.Assert(Not TimeToVibe = Nothing, $\"TimeToVibe should not be Nothing.\")\n```\n- These assertions check that critical variables are initialized correctly.\n\n```vb\nFor i As Integer = 0 To 3\n    Debug.Assert(Not Connected(i), $\"Controller {i} should not be connected after initialization.\")\n    Debug.Assert(LeftThumbstickXaxisNeutral(i), $\"Left Thumbstick X-axis for Controller {i} should be neutral.\")\n    Debug.Assert(LeftThumbstickYaxisNeutral(i), $\"Left Thumbstick Y-axis for Controller {i} should be neutral.\")\n    Debug.Assert(RightThumbstickXaxisNeutral(i), $\"Right Thumbstick X-axis for Controller {i} should be neutral.\")\n    Debug.Assert(RightThumbstickYaxisNeutral(i), $\"Right Thumbstick Y-axis for Controller {i} should be neutral.\")\n    Debug.Assert(DPadNeutral(i), $\"DPad for Controller {i} should be neutral.\")\n    Debug.Assert(LetterButtonsNeutral(i), $\"Letter Buttons for Controller {i} should be neutral.\")\nNext\n```\n- This loop checks that all controllers are initialized as not connected and that their thumbsticks and buttons are in the neutral position.\n\n[Index](#index)\n\n---\n\n### Vibrate Methods\n\n```vb\nPublic Sub VibrateLeft(CID As Integer, Speed As UShort)\n```\n- **Public Sub VibrateLeft(CID As Integer, Speed As UShort)**: This method triggers the left motor of the controller to vibrate at a specified speed.\n\n\n#### Inside the VibrateLeft Method\n\n```vb\nVibration.wLeftMotorSpeed = Speed\nLeftVibrateStart(CID) = Now\nIsLeftVibrating(CID) = True\n```\n- Sets the left motor speed, records the start time, and marks the left motor as vibrating.\n\n[Index](#index)\n\n---\n\n### SendVibrationMotorCommand Method\n\n```vb\nPrivate Sub SendVibrationMotorCommand(ControllerID As Integer)\n```\n- **Private Sub SendVibrationMotorCommand(ControllerID As Integer)**: This method sends the vibration command to the specified controller.\n\n\n#### Inside the SendVibrationMotorCommand Method\n\n```vb\nIf XInputSetState(ControllerID, Vibration) = 0 Then\n    ' The motor speed was set. Success.\nElse\n    Debug.Print($\"{ControllerID} did not vibrate.  {Vibration.wLeftMotorSpeed} |  {Vibration.wRightMotorSpeed} \")\nEnd If\n```\n- Checks if the vibration command was successful and prints a message if it failed.\n\n[Index](#index)\n\n---\n\n### UpdateVibrateTimers Method\n\n```vb\nPublic Sub UpdateVibrateTimers()\n    UpdateLeftVibrateTimer()\n    UpdateRightVibrateTimer()\nEnd Sub\n```\n- This method updates the vibration timers for both the left and right motors of the controllers.\n\n[Index](#index)\n\n---\n\n### UpdateLeftVibrateTimer Method\n\n```vb\nPrivate Sub UpdateLeftVibrateTimer()\n```\n- **Private Sub UpdateLeftVibrateTimer()**: This method checks if the left motor is still vibrating and calculates how long it has been vibrating.\n\n\n#### Inside the UpdateLeftVibrateTimer Method\n\n```vb\nFor ControllerNumber As Integer = 0 To 3\n    If IsLeftVibrating(ControllerNumber) Then\n        Dim ElapsedTime As TimeSpan = Now - LeftVibrateStart(ControllerNumber)\n        If ElapsedTime.TotalMilliseconds \u003e= TimeToVibe Then\n            IsLeftVibrating(ControllerNumber) = False\n            Vibration.wLeftMotorSpeed = 0\n        End If\n        SendVibrationMotorCommand(ControllerNumber)\n    End If\nNext\n```\n- This loop checks if the left motor is vibrating. If the elapsed time exceeds the set vibration time, it stops the vibration and sets the motor speed to zero.\n\n[Index](#index)\n\n---\n\n### UpdateRightVibrateTimer Method\n\n```vb\nPrivate Sub UpdateRightVibrateTimer()\n```\n- **Private Sub UpdateRightVibrateTimer()**: This method checks if the right motor is still vibrating and calculates how long it has been vibrating.\n\n\n#### Inside the UpdateRightVibrateTimer Method\n\n```vb\nFor ControllerNumber As Integer = 0 To 3\n\n    If IsRightVibrating(ControllerNumber) Then\n\n        Dim ElapsedTime As TimeSpan = Now - RightVibrateStart(ControllerNumber)\n\n        If ElapsedTime.TotalMilliseconds \u003e= TimeToVibe Then\n\n            IsRightVibrating(ControllerNumber) = False\n\n            Vibration.wRightMotorSpeed = 0\n\n        End If\n\n        SendVibrationMotorCommand(ControllerNumber)\n\n    End If\n\nNext\n\n```\n\n- This loop checks if the right motor is vibrating. If the elapsed time exceeds the set vibration time, it stops the vibration and sets the motor speed to zero.\n\n[Index](#index)\n\n---\n\n## Form1 Class\n\n### Class Declaration\n\n```vb\nPublic Class Form1\n    Private Controllers As XboxControllers\n```\n- **Public Class Form1**: This defines the main form of the application.\n- **Private Controllers As XboxControllers**: This variable holds an instance of the `XboxControllers` structure, allowing access to its methods and properties.\n\n[Index](#index)\n\n---\n\n### Form Load Event\n\n```vb\nPrivate Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n    InitializeApp()\n    Controllers.Initialize()\nEnd Sub\n```\n- **Private Sub Form1_Load**: This event handler is called when the form loads.\n- **InitializeApp()**: Calls the method to set up the application.\n- **Controllers.Initialize()**: Initializes the Xbox controllers.\n\n\n---\n\n### Timer Tick Event\n\n```vb\nPrivate Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick\n    Controllers.Update()\n    UpdateLabels()\n    UpdateRumbleGroupUI()\nEnd Sub\n```\n- **Private Sub Timer1_Tick**: This event handler is triggered by a timer tick event.\n- **Controllers.Update()**: Calls the update method to check the current state of the controllers.\n- **UpdateLabels()**: Updates the UI labels to reflect the current state of the controllers.\n- **UpdateRumbleGroupUI()**: Updates the UI elements related to the vibration settings.\n\n---\n\n### Button Click Events\n\n```vb\nPrivate Sub ButtonVibrateLeft_Click(sender As Object, e As EventArgs) Handles ButtonVibrateLeft.Click\n    If Controllers.Connected(NumControllerToVib.Value) Then\n        Controllers.VibrateLeft(NumControllerToVib.Value, TrackBarSpeed.Value)\n    End If\nEnd Sub\n```\n- **Private Sub ButtonVibrateLeft_Click**: This event handler is triggered when the \"Vibrate Left\" button is clicked.\n- Checks if the selected controller is connected and calls the `VibrateLeft` method with the specified speed.\n\n```vb\nPrivate Sub ButtonVibrateRight_Click(sender As Object, e As EventArgs) Handles ButtonVibrateRight.Click\n    If Controllers.Connected(NumControllerToVib.Value) Then\n        Controllers.VibrateRight(NumControllerToVib.Value, TrackBarSpeed.Value)\n    End If\nEnd Sub\n```\n- **Private Sub ButtonVibrateRight_Click**: Similar to the left vibration button, this triggers vibration on the right motor.\n\n---\n\n### TrackBar and NumericUpDown Events\n\n```vb\nPrivate Sub TrackBarSpeed_Scroll(sender As Object, e As EventArgs) Handles TrackBarSpeed.Scroll\n    UpdateSpeedLabel()\nEnd Sub\n```\n- **Private Sub TrackBarSpeed_Scroll**: This event updates the speed label based on the value selected in the trackbar.\n\n```vb\nPrivate Sub NumericUpDownTimeToVib_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDownTimeToVib.ValueChanged\n    Controllers.TimeToVibe = NumericUpDownTimeToVib.Value\nEnd Sub\n```\n- **Private Sub NumericUpDownTimeToVib_ValueChanged**: Updates the vibration duration when the numeric up/down value changes.\n\n---\n\n### UpdateLabels Method\n\n```vb\nPrivate Sub UpdateLabels()\n    For ControllerNumber As Integer = 0 To 3\n        UpdateControllerStatusLabel(ControllerNumber)\n        If Controllers.Connected(ControllerNumber) Then\n            UpdateThumbstickLabels(ControllerNumber)\n            UpdateTriggerLabels(ControllerNumber)\n            UpdateDPadLabel(ControllerNumber)\n            UpdateLetterButtonLabel(ControllerNumber)\n            UpdateStartBackLabels(ControllerNumber)\n            UpdateBumperLabels(ControllerNumber)\n            UpdateStickLabels(ControllerNumber)\n        End If\n    Next\nEnd Sub\n```\n- **Private Sub UpdateLabels**: This method updates the UI labels for each controller.\n- It loops through each controller (0 to 3) and checks if it is connected. For connected controllers, it updates various UI elements to reflect the current state of thumbsticks, buttons, and triggers.\n\n---\n\n### UpdateControllerStatusLabel Method\n\n```vb\nPrivate Sub UpdateControllerStatusLabel(controllerNumber As Integer)\n    Dim status As String = If(Controllers.Connected(controllerNumber), \"Connected\", \"Not Connected\")\n    Dim labelText As String = $\"Controller {controllerNumber} {status}\"\n    Select Case controllerNumber\n        Case 0\n            LabelController0Status.Text = labelText\n        Case 1\n            LabelController1Status.Text = labelText\n        Case 2\n            LabelController2Status.Text = labelText\n        Case 3\n            LabelController3Status.Text = labelText\n    End Select\nEnd Sub\n```\n- **Private Sub UpdateControllerStatusLabel**: This method updates the status label for each controller based on whether it is connected or not.\n\n---\n\n### Rumble Group UI Method\n\n```vb\nPrivate Sub UpdateRumbleGroupUI()\n    Dim NumberOfConnectedControllers As Integer\n    Dim HighestConnectedControllerNumber As Integer\n\n    For ControllerNumber As Integer = 0 To 3\n        If Controllers.Connected(ControllerNumber) Then\n            NumberOfConnectedControllers += 1\n            HighestConnectedControllerNumber = ControllerNumber\n        End If\n    Next\n\n    If NumberOfConnectedControllers \u003e 0 Then\n        NumControllerToVib.Maximum = HighestConnectedControllerNumber\n        RumbleGroupBox.Enabled = True\n        If Controllers.Connected(NumControllerToVib.Value) Then\n            ButtonVibrateLeft.Enabled = True\n            ButtonVibrateRight.Enabled = True\n            TrackBarSpeed.Enabled = True\n            LabelSpeed.Enabled = True\n            NumericUpDownTimeToVib.Enabled = True\n            LabelTimeToVibe.Enabled = True\n        Else\n            ButtonVibrateLeft.Enabled = False\n            ButtonVibrateRight.Enabled = False\n            TrackBarSpeed.Enabled = False\n            LabelSpeed.Enabled = False\n            NumericUpDownTimeToVib.Enabled = False\n            LabelTimeToVibe.Enabled = False\n        End If\n    Else\n        NumControllerToVib.Maximum = 0\n        RumbleGroupBox.Enabled = False\n    End If\nEnd Sub\n```\n- **Private Sub UpdateRumbleGroupUI**: This method updates the UI elements related to vibration settings based on the connected controllers.\n\n---\n\n### Additional Methods for Clearing Labels\n\nThe code contains several methods that clear labels when the respective buttons or thumbsticks are not active. These methods check the state of each controller and update the UI accordingly.\n\nIn this detailed walkthrough, we've covered the key components of the Xbox controller integration code. This code allows developers to interact with Xbox controllers, monitor their states, and provide haptic feedback through vibration. Understanding each part of this code will empower you to implement and customize Xbox controller functionality in your applications.\n\nIf you have any questions or need further clarification on specific parts of the code, feel free to ask! Happy coding!\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n---\n\n\n\n\n\n\n\n# **The Neutral Zone**\n\nThe neutral zone refers to a specific range of input values for a controller's thumbsticks or triggers where no significant action or movement is registered. This is particularly important in gaming to prevent unintentional inputs when the player is not actively manipulating the controls.\n\nThe neutral zone helps to filter out minor movements that may occur when the thumbsticks or triggers are at rest. This prevents accidental inputs and enhances gameplay precision.\n\nFor thumbsticks, the neutral zone is defined by a range of values (-16384 to 16384 for a signed 16-bit integer). Movements beyond this range are considered active inputs.\n\n![014](https://github.com/user-attachments/assets/fb9ca8ba-9b9f-4903-a994-673ff4ac1559)\n\nReduces the likelihood of unintentional actions, leading to a smoother gaming experience.\nEnhances control sensitivity, allowing for more nuanced gameplay, especially in fast-paced or competitive environments.\nUnderstanding the neutral zone is crucial for both developers and players to ensure that controller inputs are accurate and intentional.\n\n[Index](#index)\n\n---\n\n\n\n\n\n# **The Trigger Threshold**\n\nThe trigger threshold refers to the minimum amount of pressure or movement required on a controller's trigger (or analog input) before it registers as an active input. This concept is crucial for ensuring that the controller responds accurately to player actions without registering unintended inputs.\n\nThe trigger threshold helps filter out minor or unintentional movements. It ensures that only deliberate actions are registered, improving gameplay precision.\n\nFor example, in a typical game controller, the trigger may have a range of values from 0 to 255 (for an 8-bit input). A threshold might be set at 64, meaning the trigger must be pulled beyond this value to register as \"pressed.\" Values below 64 would be considered inactive.\n\n\n![009](https://github.com/user-attachments/assets/9c599b9e-a77b-4797-8ce7-345c7f3e2dc9)\n\n\nReduces accidental inputs during gameplay, especially in fast-paced scenarios where slight movements could lead to unintended actions.\nProvides a more controlled and responsive gaming experience, allowing players to execute actions more precisely.\n\nCommonly used in racing games (for acceleration and braking), shooting games (for aiming and firing), and other genres where trigger sensitivity is important.\nUnderstanding the trigger threshold is essential for both developers and players to ensure that controller inputs are intentional and accurately reflect the player's actions.\n\n\n\n\n![063](https://github.com/user-attachments/assets/42017bca-10fc-4792-a0e2-005893763b00)\n\n\n\n---\n\n## Index\n- [Imports](#imports)\n- [XboxControllers Structure](#xboxcontrollers-structure)\n\n- [DllImport for XInputGetState](#dllimport-for-xinputgetstate)\n- [XINPUT_STATE Structure](#xinput_state-structure)\n- [XINPUT_GAMEPAD Structure](#xinput_gamepad-structure)\n- [State Variable](#state-variable)\n- [Button Enumeration](#button-enumeration)\n- [Neutral Zone Constants](#neutral-zone-constants)\n- [Initialization Method](#initialization-method)\n- [Update Method](#update-method)\n- [State Update Method](#state-update-method)\n- [Button and Thumbstick Updates](#button-and-thumbstick-updates)\n- [Vibration Functions](#vibration-functions)\n- [Form Initialization](#form-initialization)\n- [Conclusion](#conclusion)\n\n\n\n---\n\n\nFeel free to experiment with the code, modify it, and add new features as you learn more about programming! If you have any questions, please post on the **Q \u0026 A Discussion Forum**, don’t hesitate to ask.\n\n---\n\n```\n\nMIT License\nCopyright(c) 2023 Joseph W. Lumbley\n\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoelumbley%2Fxinput","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjoelumbley%2Fxinput","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoelumbley%2Fxinput/lists"}