Wiimote Library for Developers on Coding4Fun

Brian Peek just published his latest article, a .NET library for easy programming of a Nintendo Wiimote controller. His article and project on Channel9 includes the full source code for the library and how he built everything. The cool part is of course how easy it is to use the library as shown below...

  1. Create a Wiimote class

     VB: Dim WithEvents wm As Wiimote = New Wiimote()
    
     C#: Wiimote wm = new Wiimote();
    
  2. Connect to the controller
    VB: wm.Connect()
    C#: wm.Connect();

  3. Add an event handler for the OnWiimoteChanged event

     VB: Private Sub wm_OnWiimoteChanged(ByVal sender As System.Object, ByVal e As WiimoteChangedEventArgs) Handles wm.OnWiimoteChanged
    
     C#: wm.OnWiimoteChanged += new WiimoteChangedEventHandler(wm_OnWiimoteChanged);
    
  4. Poll the Wiimote State

    VB/C#: wm.WiimoteState.ButtonState.A

 

You can find a Wiimote Test project that walks through all of the properties available (that's the screenshot above) in Brian's download as well. Here's a very quick example that pops a message box if you hit the A button.

VB Code that checks if Button A is pressed

 Imports WiimoteLib
 Imports System.Windows.Forms
  
 Public Class Form2
     'Wiimote Class
     Dim WithEvents wm As Wiimote = New Wiimote()
  
     Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
         wm.Connect()
     End Sub
  
     Private Sub wm_OnWiimoteChanged(ByVal sender As System.Object, ByVal e As WiimoteChangedEventArgs) Handles wm.OnWiimoteChanged
         If (wm.WiimoteState.ButtonState.A = True) Then
             MessageBox.Show("You pressed the A button!")
         End If
     End Sub
 End Class

C# Code that checks if Button A is pressed

 public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    Wiimote wm = new Wiimote();
    private void Form2_Load(object sender, EventArgs e)
    {            
        //use this to listen to Wiimote events
        wm.OnWiimoteChanged += new WiimoteChangedEventHandler(wm_OnWiimoteChanged);
        wm.Connect();
    }

    void wm_OnWiimoteChanged(object sender, WiimoteChangedEventArgs args)
    {            
        if (wm.WiimoteState.ButtonState.A == true)
        {
            MessageBox.Show("You pressed the A button!");                
        }
    }
}