+ Reply to Thread
Results 1 to 1 of 1

Thread: Console Application to change the desktop wallpaper

  1. #1
    Ask Me About Dragons :D Shadow Wizard has a spectacular aura about Shadow Wizard has a spectacular aura about Shadow Wizard's Avatar
    Join Date
    Jul 2008
    Location
    Israel
    Posts
    795
    Blog Entries
    2
    Real Name
    Yahav
    Rep Power
    5

    Console Application to change the desktop wallpaper

    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;
    }
    
    Attached Files
    Last edited by Shadow Wizard; July 30th, 2008 at 01:25 PM.

+ Reply to Thread

Similar Threads

  1. find words and change
    By todd2006 in forum JavaScript Programming
    Replies: 4
    Last Post: July 2nd, 2008, 10:58 AM
  2. desktop application
    By techker in forum Microsoft Access
    Replies: 8
    Last Post: June 9th, 2008, 10:07 PM
  3. Change to Reputation System
    By jmurrayhead in forum Announcements
    Replies: 0
    Last Post: June 2nd, 2008, 10:57 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

SEO by vBSEO