Below is the full code for console application that will change the desktop
wallpaper image.
Windows can handle only BMP images and force the image to be BMP: unlike
other codes that I found, the below code won't crash when you choose non
BMP image but instead will convert desired image to BMP format.
Another cool option that I've added is the ability to select image in random
from given folder.
Note, the code will create folder called "DesktopBackground" under My Pictures
folder of the logged in user and in there store copy of the files.
Attached is also ZIP with both the code and the ready EXE application.
The code was tested under Windows Server 2003 but should work on other
version as well, please report any problems or questions here.
Code:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SystemParametersInfo(UInt32 action, UInt32 uParam, String vParam, UInt32 winIni);
private static readonly UInt32 SPI_SETDESKWALLPAPER = 0x14;
private static readonly UInt32 SPIF_UPDATEINIFILE = 0x01;
private static readonly UInt32 SPIF_SENDWININICHANGE = 0x02;
private static readonly UInt32 SPI_GETDESKWALLPAPER = 0x73;
private static readonly int MAX_PATH = 260;
private static readonly string[] validImageFormats = new string[] { ".bmp", ".gif", ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".wmf", ".emf" };
static void Main(string[] args)
{
if (args.Length > 0)
{
if (args[0].Equals("-change", StringComparison.CurrentCultureIgnoreCase))
{
string strNewPath = (args.Length > 1) ? args[1] : String.Empty;
if (!String.IsNullOrEmpty(strNewPath))
{
if (strNewPath.Equals("-random", StringComparison.CurrentCultureIgnoreCase))
{
strNewPath = "";
string strFolderPath = (args.Length > 2) ? args[2] : String.Empty;
if (!String.IsNullOrEmpty(strFolderPath))
{
if (Directory.Exists(strFolderPath))
{
strNewPath = GetRandomImage(strFolderPath);
}
else
{
ShowErrorMessage("folder does not exist: " + strFolderPath);
}
}
else
{
ShowErrorMessage("missing folder name");
}
}
if (strNewPath.Length > 0)
{
if (File.Exists(strNewPath))
{
SetWallpaper(strNewPath);
}
else
{
ShowErrorMessage("file does not exist: " + strNewPath);
}
}
}
else
{
ShowErrorMessage("missing file name");
}
}
else if (args[0].Equals("-get", StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("current wallpaper: " + GetWallpaper());
}
else
{
ShowErrorMessage("invalid parameter: " + args[0]);
}
}
else
{
ShowErrorMessage("not enough parameters");
}
Console.WriteLine(" ");
Console.Write("press any key...");
Console.ReadLine();
}
private static void ShowErrorMessage(string strMessage)
{
Console.WriteLine(strMessage);
ShowSyntax();
}
private static void ShowSyntax()
{
string strProcessName = Process.GetCurrentProcess().ProcessName;
Console.WriteLine(" ");
Console.WriteLine("Available command line parameters:");
Console.WriteLine("-get");
Console.WriteLine(" show the disk path of current wallpaper");
Console.WriteLine(" ");
Console.WriteLine("-change [image path]");
Console.WriteLine(" change the wallpaper to the image in given path");
Console.WriteLine(" ");
Console.WriteLine("-change -random [folder path]");
Console.WriteLine(" change the wallpaper to random image file from the given folder");
Console.WriteLine(" ");
Console.WriteLine("Examples:");
Console.WriteLine(String.Format(" {0} -get", strProcessName));
Console.WriteLine(String.Format(" {0} -change C:\\mypictures\\coolpicture.jpg", strProcessName));
Console.WriteLine(String.Format(" {0} -change -random C:\\mypictures", strProcessName));
}
public static void SetWallpaper(String path)
{
try
{
Console.WriteLine("setting wallpaper to the file " + path + "...");
string strBitmapPath = CopyBitmap(path);
if (!String.IsNullOrEmpty(strBitmapPath))
{
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, strBitmapPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
Console.WriteLine("wallpaper set successfully to " + strBitmapPath);
}
else
{
Console.WriteLine("action aborted");
}
}
catch (Exception ex)
{
Console.WriteLine("error while setting wallpaper: " + ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
private static string GetRandomImage(string strFolderPath)
{
string[] arrAllImages = GetAllImages(strFolderPath);
if (arrAllImages == null || arrAllImages.Length == 0)
{
Console.WriteLine("the folder '" + strFolderPath + "' does not contain valid images");
Console.WriteLine("valid image formats: " + String.Join(", ", validImageFormats));
return String.Empty;
}
int rndIndex = (new Random()).Next(0, arrAllImages.Length);
return arrAllImages[rndIndex];
}
private static string[] GetAllImages(string strFolderPath)
{
List<string> arrImageFiles = new List<string>();
DirectoryInfo dirInfo = new DirectoryInfo(strFolderPath);
foreach (FileInfo file in dirInfo.GetFiles())
{
if (IsImageFile(file))
{
arrImageFiles.Add(file.FullName);
}
}
return arrImageFiles.ToArray();
}
private static bool IsImageFile(FileInfo file)
{
string strExtension = Path.GetExtension(file.Name).ToLower();
return (Array.IndexOf<string>(validImageFormats, strExtension) >= 0);
}
private static string CopyBitmap(string originalImagePath)
{
Bitmap bitmap = null;
try
{
bitmap = new Bitmap(originalImagePath);
}
catch
{
Console.WriteLine(originalImagePath + " is not valid bitmap!");
return null;
}
string strNewImagePath = GetLocalPath(originalImagePath);
Console.WriteLine(String.Format("trying to copy the file '{0}' to '{1}'...", originalImagePath, strNewImagePath));
try
{
bitmap.Save(strNewImagePath, ImageFormat.Bmp);
Console.WriteLine("saved successfully");
}
catch (Exception ex)
{
Console.WriteLine("error while saving: " + ex.Message);
return null;
}
return strNewImagePath;
}
private static string GetLocalPath(string originalPath)
{
string strRootFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
string strLocalFolderPath = strRootFolderPath + Path.DirectorySeparatorChar + "DesktopBackground";
if (!Directory.Exists(strLocalFolderPath))
{
Console.WriteLine("creating the directory " + strLocalFolderPath + "...");
Directory.CreateDirectory(strLocalFolderPath);
Console.WriteLine("created successfully");
}
return strLocalFolderPath + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(originalPath) + ".bmp";
}
private static string GetImageFormat(Bitmap bitmap)
{
ImageFormat format = bitmap.RawFormat;
if (format.Equals(ImageFormat.Bmp))
return "bmp";
if (format.Equals(ImageFormat.Emf))
return "emf";
if (format.Equals(ImageFormat.Exif))
return "exif";
if (format.Equals(ImageFormat.Gif))
return "gif";
if (format.Equals(ImageFormat.Icon))
return "icon";
if (format.Equals(ImageFormat.Jpeg))
return "jpeg";
if (format.Equals(ImageFormat.MemoryBmp))
return "memorybmp";
if (format.Equals(ImageFormat.Png))
return "png";
if (format.Equals(ImageFormat.Tiff))
return "tiff";
if (format.Equals(ImageFormat.Wmf))
return "wmf";
return null;
}
public static String GetWallpaper()
{
String wallpaper = new String('\0', MAX_PATH);
SystemParametersInfo(SPI_GETDESKWALLPAPER, (UInt32)wallpaper.Length, wallpaper, 0);
wallpaper = wallpaper.Substring(0, wallpaper.IndexOf('\0'));
return wallpaper;
}