Tuesday 22 January 2013

Set Wallpaper using C#

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

namespace CustomWallpaper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private static readonly UInt32 SPI_SETDESKWALLPAPER = 0x14;
        private static readonly UInt32 SPIF_UPDATEINIFILE = 0x01;
        private static readonly UInt32 SPIF_SENDWININICHANGE = 0x02;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern Int32 SystemParametersInfo(
            UInt32 action, UInt32 uParam, String vParam, UInt32 winIni);

        private void Form1_Load(object sender, EventArgs e)
        {
            string strPath = "D:\\Projects\\Wallpaper\\Wallpaper.jpg";

            
            if (File.Exists(strPath))
            {
                SetWallpaper(strPath);
            }
            else
            {
                 strPath = "D:\\Projects\\Wallpaper\\Wallpaper.jpeg";
                if (File.Exists(strPath))
                { 
                    SetWallpaper(strPath); 
                }
                else
                {
                    strPath = "D:\\Projects\\Wallpaper\\Wallpaper.png";
                    if (File.Exists(strPath))
                    {
                        SetWallpaper(strPath); 
                    }
                    else
                    {
                        MessageBox.Show("Wallpaper.jpg Or Wallpaper.jpeg OR Wallpaper.png is not found on this path D:\\Projects\\Wallpaper\\");
                        this.Close();
                    }
                }
            }
        }

        private void SetWallpaper(string path)
        {
            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path,SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);            
            key.SetValue(@"WallpaperStyle", 2.ToString());
            key.SetValue(@"TileWallpaper", 0.ToString());            
            this.Close();
        }
    }
}


No comments:

Post a Comment