Wallpaper
The desktop wallpaper is the background image for Microsoft Windows that is visible behind any open windows. All versions of Windows that support the .NET framework allow a static desktop wallpaper to be applied but not all allow the image to be changed automatically.In this
post we will create a C# class
that sets the desktop wallpaper image. You could use this as the basis
for a program that cycles through multiple wallpapers with regular
changes. Unfortunately, the .NET framework does not natively support
setting the background image so we need to use a Windows API function.Referencing the API
As we will be using a Windows API function we will need to use Platform Invocation Services (P/Invoke). The attributes that we need are in the System.Runtime.InteropServices namespace.
Constant Parameters
SystemParametersInfo can be used to retrieve or change a number of
operating system settings. To determine which item is being configured,
you pass an integer value to the uiAction parameter. To change the wallpaper, the value is defined in a constant named, "SPI_SETDESKTOPWALLPAPER". The uiParam parameter is unused when changing the wallpaper and so should be set to zero. The pvParam parameter is used. We will pass the file path and name into it.The final argument, fWinIni, determines how the change is written to user profile and whether a message should be sent to other windows to notify them of the update. We will be updating the profile using the SPIF_UPDATEINIFILE constant.
The Windows API function that we will use to change the wallpaper is SystemParametersInfo and is found in the user32 API. To provide access to it, create a class named "WallpaperSetter"
with the following code:using System;
using System.Runtime.InteropServices;
namespace Wallpaper
{
public class WallpaperSetter
{
[DllImport("user32.dll")]
private static extern bool SystemParametersInfo(uint uiAction, uint uiParam, string pvParam, uint fWinIni);
const uint SPI_SETDESKWALLPAPER = 0x14;
const uint SPIF_UPDATEINIFILE = 0x01;
public void SetWallpaper(string path)
{
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE);
}
}
}
No comments:
Post a Comment