Modifier le papier peint du bureau à l’aide du code dans .NET

Comment puis-je changer le fond d’écran à l’aide du code C #?

Voici une classe tirée d’une application que j’ai écrite il y a un an ou deux:

public sealed class Wallpaper { Wallpaper() { } const int SPI_SETDESKWALLPAPER = 20; const int SPIF_UPDATEINIFILE = 0x01; const int SPIF_SENDWININICHANGE = 0x02; [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int SystemParametersInfo(int uAction, int uParam, ssortingng lpvParam, int fuWinIni); public enum Style : int { Tiled, Centered, Stretched } public static void Set(Uri uri, Style style) { System.IO.Stream s = new System.Net.WebClient().OpenRead(uri.ToSsortingng()); System.Drawing.Image img = System.Drawing.Image.FromStream(s); ssortingng tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp"); img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp); RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true); if (style == Style.Stretched) { key.SetValue(@"WallpaperStyle", 2.ToSsortingng()); key.SetValue(@"TileWallpaper", 0.ToSsortingng()); } if (style == Style.Centered) { key.SetValue(@"WallpaperStyle", 1.ToSsortingng()); key.SetValue(@"TileWallpaper", 0.ToSsortingng()); } if (style == Style.Tiled) { key.SetValue(@"WallpaperStyle", 1.ToSsortingng()); key.SetValue(@"TileWallpaper", 1.ToSsortingng()); } SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); } } 

Je ne l’ai pas testé de manière approfondie, donc utilisez-le à vos risques et périls.

Basée sur cette réponse utile , j’ai également créé ma propre application pour définir la résolution d’écran correspondant au fond d’écran.

Mais les parameters du registre étaient incorrects. Voici les valeurs correctes (testées sur Win 7, Win 8.1, Win 10).

 if (style == Style.Fill) { key.SetValue(@"WallpaperStyle", 10.ToSsortingng()); key.SetValue(@"TileWallpaper", 0.ToSsortingng()); } if (style == Style.Fit) { key.SetValue(@"WallpaperStyle", 6.ToSsortingng()); key.SetValue(@"TileWallpaper", 0.ToSsortingng()); } if (style == Style.Span) // Windows 8 or newer only! { key.SetValue(@"WallpaperStyle", 22.ToSsortingng()); key.SetValue(@"TileWallpaper", 0.ToSsortingng()); } if (style == Style.Stretch) { key.SetValue(@"WallpaperStyle", 2.ToSsortingng()); key.SetValue(@"TileWallpaper", 0.ToSsortingng()); } if (style == Style.Tile) { key.SetValue(@"WallpaperStyle", 0.ToSsortingng()); key.SetValue(@"TileWallpaper", 1.ToSsortingng()); } if (style == Style.Center) { key.SetValue(@"WallpaperStyle", 0.ToSsortingng()); key.SetValue(@"TileWallpaper", 0.ToSsortingng()); } 

Tweaking la réponse de Neal N pour les gifs:

 private const int SPI_SETDESKWALLPAPER = 20; private const int SPIF_UPDATEINIFILE = 0x01; private const int SPIF_SENDWININICHANGE = 0x02; [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SystemParametersInfo(int uAction, int uParam, ssortingng lpvParam, int fuWinIni); public enum Style : int { Tiled, Centered, Stretched } ///  /// Loops numFrames times, animating the desktop background as the given gif. /// Remember this will sorta bog down your computer, and probably isn't best to be running 24/7. /// If numFrames is negative this will loop forever ///  /// The gif to be animated /// If the gif has transparency, it will be "replaced" with this color. /// How many frames to play per second. This is a max: most likely it will be a little slower than this especially at first. /// Whether to tile, center, or stretch each gif frame as it's played. /// The number of frames to play. If negative, this method will loop forever. public static void SetDesktopBackgroundAsGifAsync(ssortingng gifPath, System.Drawing.Color transparencyReplace, int framesPerSecond, Style style, int numFrames) { Thread workerThread = new Thread(() => SetDesktopBackgroundAsGif(gifPath, transparencyReplace, framesPerSecond, style, numFrames)); workerThread.Start(); } ///  /// Loops numFrames times, animating the desktop background as the given gif. /// Remember this will sorta bog down your computer, and probably isn't best to be running 24/7. /// If num frames is negative this will loop forever. ////  /// The gif to be animated /// Image to render the gif on top of (because of transparency) /// How many frames to play per second. This is a max: most likely it will be a little slower than this. /// Whether to tile, center, or stretch each gif frame as it's played. /// The number of frames to play. If negative, this method will loop forever. public static void SetDesktopBackgroundAsGifAsync(ssortingng gifPath, System.Drawing.Image backgroundImage, int framesPerSecond, Style style, int numFrames) { Thread workerThread = new Thread(() => SetDesktopBackgroundAsGif(gifPath, backgroundImage, framesPerSecond, style, numFrames)); workerThread.Start(); } ///  /// Loops numFrames times, animating the desktop background as the given gif. /// Remember this will sorta bog down your computer, and probably isn't best to be running 24/7. /// if numFrames is negative this will loop forever ///  /// The gif to be animated /// If the gif has transparency, it will be "replaced" with this color. /// How many frames to play per second. This is a max: most likely it will be a little slower than this. /// Whether to tile, center, or stretch each gif frame as it's played. /// The number of frames to play. If negative, this method will loop forever. public static void SetDesktopBackgroundAsGif(ssortingng gifPath, System.Drawing.Color transparencyReplace, int framesPerSecond, Style style, int numFrames) { if (!File.Exists(gifPath)) throw new Exception("Given gif: '" + gifPath + "' not found"); FileStream gifFile = new FileStream(gifPath, FileMode.Open); GifBitmapDecoder gifDecoder = new GifBitmapDecoder(gifFile, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); if (gifDecoder.Frames.Count == 0) throw new Exception("No frames in given gif"); Bitmap backgroundImage = new Bitmap(gifDecoder.Frames[0].PixelWidth, gifDecoder.Frames[0].PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using(Graphics g = Graphics.FromImage(backgroundImage)) { g.FillRectangle(new System.Drawing.SolidBrush(transparencyReplace), 0, 0, gifDecoder.Frames[0].PixelWidth, gifDecoder.Frames[0].PixelHeight); } gifFile.Close(); SetDesktopBackgroundAsGif(gifPath, backgroundImage, framesPerSecond, style, numFrames); } ///  /// Loops infinitely, animating the desktop background as the given gif. /// Remember this will sorta bog down your computer, and probably isn't best to be running 24/7. ///  /// The gif to be animated /// Image to render the gif on top of (because of transparency) /// How many frames to play per second. This is a max: most likely it will be a little slower than this. /// Whether to tile, center, or stretch each gif frame as it's played. /// The number of frames to play. If negative, this method will loop forever. private static void SetDesktopBackgroundAsGif(ssortingng gifPath, System.Drawing.Image backgroundImage, int framesPerSecond, Style style, int numFrames) { if (!File.Exists(gifPath)) throw new Exception("Given gif: '" + gifPath + "' not found"); FileStream gifFile = new FileStream(gifPath, FileMode.Open); GifBitmapDecoder gifDecoder = new GifBitmapDecoder(gifFile, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); if (gifDecoder.Frames.Count == 0) throw new Exception("No frames in given gif"); Console.WriteLine("Saving frames to temporary files:"); int numFramesSoFar = 0; for (int i = 0; i < gifDecoder.Frames.Count; i++) { BitmapFrame gifFrame = gifDecoder.Frames[i]; PngBitmapEncoder pngEncoder = new PngBitmapEncoder(); pngEncoder.Frames.Add(gifFrame); MemoryStream pngStream = new MemoryStream(); pngEncoder.Save(pngStream); Image frameImage = Image.FromStream(pngStream); Bitmap bmp = new Bitmap(frameImage.Width, frameImage.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmp)) { g.DrawImage(backgroundImage, 0, 0); g.DrawImageUnscaled(frameImage, 0, 0); } string tempPath = Path.Combine(Path.GetTempPath(), gifPath + i + ".bmp"); bmp.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp); Console.WriteLine("Saved frame " + i); numFramesSoFar++; if (numFrames >= 0 && numFramesSoFar >= numFrames) break; } Console.WriteLine("Setting frames to desktop background at about " + framesPerSecond + " FPS"); // 1.0/... to convert to seconds per frame (instead of frames per second) // * 1000 to convert to milliseconds per frame // * 1000 to convert to microseconds per frame // * 10 to convert to 0.1s of microseconds per frame = 100s of nanoseconds per frame long ticksBetweenFrames = (long)Math.Round(1.0 / framesPerSecond) * 1000*1000*10; Stopwatch timer = new Stopwatch(); timer.Start(); numFramesSoFar = 0; while(numFrames < 0 || numFramesSoFar < numFrames) { for (int i = 0; i < gifDecoder.Frames.Count; i++) { // Sleep until we're at the desired frame rate, if needed. if(ticksBetweenFrames > timer.ElapsedTicks) Thread.Sleep(new TimeSpan(Math.Max(0, ticksBetweenFrames - timer.ElapsedTicks))); timer.Restart(); // From http://soffr.miximages.com/c%23/2924421 ssortingng filePath = Path.Combine(Path.GetTempPath(), wallpaper   i   .bmp"); RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true); if (style == Style.Stretched) { key.SetValue(@"WallpaperStyle", 2.ToSsortingng()); key.SetValue(@"TileWallpaper", 0.ToSsortingng()); } if (style == Style.Centered) { key.SetValue(@"WallpaperStyle", 1.ToSsortingng()); key.SetValue(@"TileWallpaper", 0.ToSsortingng()); } if (style == Style.Tiled) { key.SetValue(@"WallpaperStyle", 1.ToSsortingng()); key.SetValue(@"TileWallpaper", 1.ToSsortingng()); } SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, filePath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); numFramesSoFar++; if (numFrames >= 0 && numFramesSoFar >= numFrames) break; } } gifFile.Close(); } 

Notez également que vous devez utiliser:

 using Microsoft.Win32; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; 

Enfin, cliquez avec le bouton droit de la souris sur votre projet, ajoutez une référence et (dans Assemblys and Framework) ajoutez Presentation Core, System.Xaml et WindowsBase.

Cliquez ensuite avec le bouton droit de la souris sur votre projet et accédez à Propriétés, et vérifiez que Target Framework est .Net Framework 4.5. Si vous changez cela, vous devrez peut-être redémarrer Visual Studio.