Skip to content

Instantly share code, notes, and snippets.

@zhaoguohao
Forked from EricJ2190/RandomWallpaper.cs
Created March 6, 2024 12:57
Show Gist options
  • Save zhaoguohao/93a9ec626acd754ca81463581fb48274 to your computer and use it in GitHub Desktop.
Save zhaoguohao/93a9ec626acd754ca81463581fb48274 to your computer and use it in GitHub Desktop.
Random Windows Wallpaper
/* Selects a random image from a folder and makes it the desktop wallpaper.
* usage: RandomWallpaper.exe [c:\path\to\wallpapers]
* If the path is omitted, the current directory is used.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
namespace RandomWallpaper
{
class Program
{
[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 = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;
static void Main(string[] args)
{
DirectoryInfo directory;
if (args.Length < 1) directory =
new DirectoryInfo(Directory.GetCurrentDirectory());
else directory = new DirectoryInfo(args[0]);
List<FileInfo> files = new List<FileInfo>();
foreach (String ext in new String[]
{"bmp", "jpg", "jpeg", "png", "gif", "tif", "tiff"})
files.AddRange(directory.GetFiles("*." + ext));
if (files.Count == 0) MessageBox.Show("No images found.");
else {
String pic = files[new Random().Next(files.Count)].FullName;
String path = Path.GetTempPath() + "RandomWallpaper.bmp";
Image image = Image.FromFile(pic);
image.Save(path, ImageFormat.Bmp);
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment