How do I change my Windows desktop wallpaper programmatically?

后端 未结 2 898
温柔的废话
温柔的废话 2020-12-23 15:14

I\'d wish to set a wallpaper for Windows XP using C#. I\'ve developed the code so it perfectly works in Windows 7, but apparently it\'s not the same for XP. I add that wallp

2条回答
  •  太阳男子
    2020-12-23 16:12

    Well, this is a bit awkward, but I'll answer my own question with what I found.

    I had to reuse more code from the accepted answer here. Basically the problem in XP was that it needed to use a bmp file, so I managed to convert a project resource to a bmp file using that previous example and a little of tweaking. The Set method works perfectly this way:

    public static void Set(string wpaper, Style style)
    {
        using(System.Drawing.Image img = System.Drawing.Image.FromFile(Path.GetFullPath(wpaper)))
        {
            string 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.ToString());
    
            key.SetValue(@"TileWallpaper", 0.ToString());
    
        }
    
        if (style == Style.Centered)
        {
            key.SetValue(@"WallpaperStyle", 1.ToString());
    
            key.SetValue(@"TileWallpaper", 0.ToString());
    
        }
    
        if (style == Style.Tiled)
        {
            key.SetValue(@"WallpaperStyle", 1.ToString());
    
            key.SetValue(@"TileWallpaper", 1.ToString());
    
        }
    
        SystemParametersInfo(SPI_SETDESKWALLPAPER,
            0,
            tempPath,
            SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
    
    }
    

    The important part is on the third line of this code (System.Drawing.Image.FromFile(Path.GetFullPath(wpaper));).

提交回复
热议问题