using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTunesLib;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
/* TODO:
* - Hide console window
* - Debug event firing
* - Change icon
* - Traverse to genius recommendations?
*/
namespace iTunesPlaylistTrayApp
{
public class SysTrayApp : Form
{
[STAThread]
public static void Main()
{
Application.Run(new SysTrayApp());
}
static iTunesApp itapp;
static IITLibraryPlaylist lastPlaylist;
public NotifyIcon trayIcon;
private ContextMenu trayMenu;
public SysTrayApp()
{
// Create a simple tray menu with only one item.
trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Exit", OnExit);
// Create a tray icon. In this example we use a
// standard system icon for simplicity, but you
// can of course use your own custom icon too.
trayIcon = new NotifyIcon();
trayIcon.Text = "Play Genius Playlist";
trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40);
trayIcon.Click += new EventHandler(trayIcon_Click);
// Add menu to tray icon and show it.
trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;
}
void trayIcon_Click(object sender, EventArgs e)
{
PlayPlaylist();
}
//private static ManualResetEvent _resetEvent;
public static void PlayPlaylist()
{
//_resetEvent = new ManualResetEvent(false);
itapp = new iTunesApp();
itapp.OnPlayerStopEvent += new _IiTunesEvents_OnPlayerStopEventEventHandler(itapp_OnPlayerStopEvent);
lastPlaylist = itapp.LibraryPlaylist;
itapp.Play();
// Block until the resetEvent has been Set() or
// give up waiting after 5 minutes
//_resetEvent.WaitOne(1000 * 5 * 60);
}
static void itapp_OnPlayerStopEvent(object iTrack)
{
Debug.WriteLine("Stop Event fired");
// Determine whether the user fired the event, or whether the song finished on its own.
// if the song finished on its own (i.e. player reset to 0 seconds)
if (itapp.PlayerPosition == 0)
{
var curList = itapp.CurrentPlaylist;
// If it's still in the (genius) playlist it started out in, and it's not the last song in the playlist
if (curList == lastPlaylist && itapp.CurrentTrack != curList.Tracks[curList.Tracks.Count - 1])
{
itapp.NextTrack();
itapp.Play();
}
}
}
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
base.OnLoad(e);
}
private void OnExit(object sender, EventArgs e)
{
Application.Exit();
}
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
// Release the icon resource.
trayIcon.Dispose();
}
base.Dispose(isDisposing);
}
}
}