iTunes Auto Updating Now Playing in VB2005

Previously I’ve covered how to link into the iTunes COM library from VB 2005 to show now playing information. This article assumes you have already read that, or have it to hand.

Taking this application further, wouldn’t it be useful for our application to automatically update itself when a track changes takes place on iTunes?

Well I hope you are saying yes, as it’s what I’m going to cover now.

iTunes can inform our application of changes of track if we choose to listen for it’s OnPlayerPlayEvent event.

If you are not sure what an event is, it’s basically a way for one program to tell another that something has happened in that program and the other program may wish to react to it. In this case, a different track has started playing in iTunes.

So how can we get our application to listen out for this? Well firstly we need to say that our programme is interested in these events. We do this by using VB 2005’s WithEvents keyword when we create our interface into iTunes.

So previously we did this using the following code.

Dim app As New iTunesApp()

Now we have to add in the WithEvents keyword as follows.

Private WithEvents app As New iTunesApp

Now our program can listen out for events from iTunes. You may have noticed I’ve changed Dim to Private. This is because for this example I’m going to use a Windows Application and not a Console application as before.

Next we have to create our event handler so we can react to the events iTunes is sending us.

The easiest way to do this is use the method generator at the top of the code view in Visual Basic 2005 Express Edition. My iTunes object is called app so we select this, then OnPlayerPlayEvent to create our event handler stub.

Creating an iTunes event in VB2005

This passes in the variable iTrack as an Object. We know this is really an IITTrack object, so we need to cast it as such.

Dim track As IITTrack
track = CType(iTrack, IITTrack)

This creates a new varible called track and casts the existing iTrack variable as an IITTrack using CType.
Doing this, we have easy access to the track data passed to us by iTunes in the event.
We need to do something with this information seeing as we’ve gone to all the trouble of asking iTunes for it. The easiest thing to do is to just display a small window with the name of the current track.

MsgBox(track.name)

Obviously this is a simplified version of a real program, but it should give you an idea of how to get events from a remote program into your VB2005 application.