Do you get fed up looking at the same desktop wallpaper day after day? Yeah, me too, so I wrote a little C# console application that reads a flickr feed of images, picks one at random and then sets it as your desktop wallpaper. Now all I need to do is to set it up as a scheduled task to run a couple of times a day and I'll get a nice new wallpaper to look at. :-) For those who are interested, the salient code is below.

class Program
{
    //Define constants we'll use later
    public const string RSS_URI = "YOUR_FLICKR_RSS_URI_HERE";

    //Define the external function we need
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern Int32 
        SystemParametersInfo(UInt32 uiAction, UInt32 uiParam, 
        String pvParam, UInt32 fWinIni);
    private static UInt32 SPI_SETDESKWALLPAPER = 20;
    private static UInt32 SPIF_UPDATEINIFILE = 0x1;
    
    //Application entry point
    static void Main(string[] args)
    {
        //Download RSS info
        XPathDocument xpd = null;
        try
        {
            xpd = new XPathDocument(RSS_URI);
        }
        catch (XmlException xe)
        {
            Console.Write("The following xml error " +
            "occurred: " + xe.Message);
            return;
        }

        //Create a name space manager 
        //and add the media namespace
        XPathNavigator xpn = xpd.CreateNavigator();
        XmlNamespaceManager nsm = 
            new XmlNamespaceManager(xpn.NameTable);
        nsm.AddNamespace("media", 
            "http://search.yahoo.com/mrss/");
        
        //Select all image URLs
        XPathNodeIterator ni = null;
        try
        {
            ni = xpn.Select(
                @"/rss/channel/item/media:content",nsm);
        }
        catch (XPathException xpe)
        {
            Console.Write("The following XPath exception " +
                "occurred: " + xpe.Message);
            return;
        }

        //Download an image at random
        Random rng = new Random(DateTime.Now.Millisecond);
        int randomInt = rng.Next(0, ni.Count+1);
        int i = 0;
        while (i < randomInt)
        {
            ni.MoveNext();
            i++;
        }
        string imageURL = 
            ni.Current.GetAttribute("url", String.Empty);

        WebClient wc = new WebClient();
        try
        {
            wc.DownloadFile(imageURL, "temp.jpg");
        }
        catch (WebException we)
        {
            Console.Write("The following web exception " +
                "occurred: " + we.Message);
            return;
        }

        //Convert image to BMP
        Image bmp = Image.FromFile("temp.jpg");
        bmp.Save("temp.bmp", ImageFormat.Bmp);
         
        //Set image as desktop wallpaper
        SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, 
            "temp.bmp",SPIF_UPDATEINIFILE);
    }
}
Technorati tags: , , , ,