Introduction
This is a simple Windows service which switches the wallpapers at configured intervals.
Background
The intention of this article is to make my/your free time a little bit useful.
Using the Code
The start()
method of this Windows service does the configuration and starts the timer. The ConfigReader
class is for reading the XML file which is included in the attached zip file.
public void Start()
{
configPath = Assembly.GetExecutingAssembly().Location;
int i = configPath.LastIndexOf("\\");
configPath = configPath.Substring(0, i) + "\\AppConfig.xml";
// Create, configure & Start timer
t = new Timer(1000 * double.Parse(WallpaperChanger.ConfigReader.GetConfigValue
(configPath, "TimerIntervalSeconds")));
t.Elapsed += new ElapsedEventHandler(t_Elapsed);
//Get the image files in an array
arrFiles = System.IO.Directory.GetFiles(WallpaperChanger.ConfigReader.GetConfigValue
(configPath, "WallpaperDirectory"), "*.bmp",
System.IO.SearchOption.AllDirectories);
t.Start();
}
Assembly.GetExecutingAssembly().Location
gives you the path of the current assembly. AppConfig.xml configuration file has the interval and the directory of the wallpapers. This AppConfig.xml should be in the same directory of the EXE file.
t = new Timer(1000 * double.Parse
(WallpaperChanger.ConfigReader.GetConfigValue(configPath, "TimerIntervalSeconds")));
This line initializes the timer with the configured interval from AppConfig.xml.
t.Elapsed += new ElapsedEventHandler(t_Elapsed);
Create a handler for Elapsed
event will be fired at every interval:
arrFiles = System.IO.Directory.GetFiles(WallpaperChanger.ConfigReader.GetConfigValue
(configPath, "WallpaperDirectory"), "*.bmp", System.IO.SearchOption.AllDirectories);
This line gets the full path of all the BMP image files in the directory which is configured in the AppConfig.xml.
t.Start();
starts the timer.
The t_Elapsed()
method will be called based on the configured regular interval. This function does the main job as stated in this article's title.
void t_Elapsed(object sender, ElapsedEventArgs e)
{
if (currentIndex < arrFiles.Length)
{
WinAPI.SystemParametersInfo(WinAPI.SPI_SETDESKWALLPAPER, 1,
arrFiles[currentIndex], WinAPI.SPIF_SENDCHANGE);
currentIndex++;
}
else
{
currentIndex = 0;
}
}
The WINAPI
class is shown below:
public class WinAPI
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SystemParametersInfo
(int uAction, int uParam, string lpvParam, int fuWinIni);
public const int SPI_SETDESKWALLPAPER = 20;
public const int SPIF_SENDCHANGE = 0x2;
}
The following system call sets the desktop with the image file given in arrFiles[currentIndex]
.
WinAPI.SystemParametersInfo(WinAPI.SPI_SETDESKWALLPAPER, 1,
arrFiles[currentIndex], WinAPI.SPIF_SENDCHANGE);
Points of Interest
This is meant to make you smile. If it does not, this article is not for you.
History
- 28th November, 2007: Initial post