Thursday, January 5, 2012

C# : Change Windows Wallpaper

Hi,

I like to change everyday my desktop wallpaper, so i've made a little soft which change it by downloading some pictures on internet.

Here my C# class to apply my wallpaper ( bmp file ) :

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using Microsoft.Win32;

namespace WallPaperChanger
{


    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;
    }

     [Serializable]
    public class WallPaperEntry
    {
 
        public enum Style : int
        {
            Tiled, Centered, Stretched
        }
 
        public static Style ImageStyle = Style.Stretched;
  
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SystemParametersInfo(
            int uAction, int uParam, string lpvParam, int fuWinIni);
 
        const int SPI_SETDESKWALLPAPER = 20;
        const int SPIF_UPDATEINIFILE = 0x1;
        const int SPIF_SENDWININICHANGE = 0x2;
 
 
        public static void ApplyWallpaper(String bPath)
        {    
            RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
 
            switch( ImageStyle )
            {
                case Style.Stretched : 
                    key.SetValue(@"WallpaperStyle", "2") ;
                     key.SetValue(@"TileWallpaper", "0") ; 
                    break; 
                case Style.Centered : 
                    key.SetValue(@"WallpaperStyle", "1") ; 
                    key.SetValue(@"TileWallpaper", "0") ; 
                    break; 
                case Style.Tiled : 
                    key.SetValue(@"WallpaperStyle", "1") ; 
                    key.SetValue(@"TileWallpaper", "1") ; 
                    break; 
            }
             key.Close();
            WinAPI.SystemParametersInfo(WinAPI.SPI_SETDESKWALLPAPER, 1,
          bPath, WinAPI.SPIF_SENDCHANGE); 
        }
    }
}

To use this class, just select the ImageStyle from Style enum and call ApplyWallpaper method :
     WallPaperEntry.ImageStyle = Style.Stretched;
     WallPaperEntry.ApplyWallpaper("C:/mywallpaper.bmp");

That's all :)

No comments:

Post a Comment