Wednesday, July 14, 2010

Change Desktop Wallpaper

This post shows, how to change the desktop wallpaper using C#.
For this, one has to include the WinAPI function SystemParametersInfo(). Its signature looks as follows:
SystemParametersInfo(UInt32 uiAction, UInt32 uiParam, String pvParam, UInt32 fWinIni)

This function is very all-rounded and make for setting general system parameters, the exact action is set by the first parameter. Possible values can be looked up here here, 4 for example describes activating / deactivating the system alarm tome and 20 change the wallpaper.
As 2nd parameter the function can be given an integer, which is not needed here. But we need the 3rd parameter, which here describes the path to the image, which is to be the new wallpaper. This file has to have the format .bmp.
The last parameter, fWinIni, describes, how the changes are to be made. The here used 0x01 says, that the new value of the parameter is to be written in the user profe. Possible values of this parameter can be viewed here.
Take a look at this sample implementation (using System.Runtime.InteropServices; required):

        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;

        private void button1_Click(object sender, EventArgs e)
            string Filename = "C:\\1.bmp";
            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, Filename, SPIF_UPDATEINIFILE);

On Udo's Blog you can find a nice use of this function, namely a program which changes the desktop background depending on the current time.

No comments:

Post a Comment