AdSense

Wednesday 24 July 2013

Windows 7 - Desktop background depending on time of day with C#

(Deutsche Version) I wanted to have a desktop background which changes depending on the time of day. Windows is not able to do this and I did not want to install software. Luckily, I found a solution with C#.

I created a folder which contains 24 files: 00.jpg, 01.jpg, ... 23.jpg. These files are for the corresponding hours during the day (00.jpg is for 0 to 1 o'clock). The desktop background is set via C#, as described here. This is my code:

Ich wollte unbedingt einen Tageszeitabhängigen Hintergrund am PC haben. Windows kann das prinzipiell nicht, und ich wollte auch keine fremde Software installieren. Mit ein paar Zeilen C# war es dann jedoch ganz einfach möglich.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.InteropServices;

namespace TimeDependantBg
{
    class Program
    {
        [DllImport("user32.dll")]
        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;

        static void Main(string[] args)
        {
            int hour;
            string basePath = @"C:\Users\Udo\TimeDependantBg\";
            string fileName;
            while (true)
            {
                hour = DateTime.Now.Hour;

                fileName = basePath + (hour % 24).ToString("00") + ".jpg";

                if (System.IO.File.Exists(fileName))
                {
                    SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, fileName, SPIF_UPDATEINIFILE);
                }
                object lockObj = new object();
                lock (lockObj)
                {
                    Monitor.Wait(lockObj, 100000);// ms, check every 100 seconds
                }
            }
        }
    }
}


Afterwards, a shortcut to TimeDependantBg.exe is created in C:\Users\Udo\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup so the program will be started when the computer is starting.

No comments:

Post a Comment