Go Back   DeveloperBarn Forums > Programming & Scripting > Code Samples

Sponsored Links

Discuss "Console Application to change the desktop wallpaper" in the Code Samples forum.

Code Samples - Search through our code samples to give your application that something extra or provide a code sample of your own.


Reply « Previous Thread | Next Thread »  
 
LinkBack Thread Tools Display Modes
  #1  
Old July 30th, 2008, 12:23 PM
Shadow Wizard's Avatar
Ask Me About Dragons :D

 
Join Date: Jul 2008
Posts: 23
Thanks: 0
Thanked 4 Times in 4 Posts
Blog Entries: 1
Rep Power: 1
Shadow Wizard is on a distinguished road

Awards Showcase
Microsoft .Net Classic ASP JavaScript 
Total Awards: 3

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

Comments on this post
jmurrayhead agrees: Pretty cool, Shad
Attached Files
File Type: zip WallPaperManager.zip (6.9 KB, 11 views)

Last edited by Shadow Wizard; July 30th, 2008 at 12:25 PM.
Reply With Quote
Sponsored Links
Reply

  DeveloperBarn Forums > Programming & Scripting > Code Samples

Bookmarks

Tags
change, console application, wallpaper

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
ASP.Net Application Design RSS User DeveloperBarn Blogs 0 August 20th, 2008 08:44 PM
find words and change todd2006 JavaScript Programming 4 July 2nd, 2008 09:58 AM
desktop application techker Microsoft Access 8 June 9th, 2008 09:07 PM
Change to Reputation System jmurrayhead Announcements 0 June 2nd, 2008 09:57 PM


All times are GMT -4. The time now is 08:26 PM.



Content Relevant URLs by vBSEO 3.2.0