如何使用C#代码更改桌面壁纸?

推荐答案

以下是我一两年前编写的一款应用程序中的一个课程:

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, string 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.ToString());

        System.Drawing.Image img = System.Drawing.Image.FromStream(s);
        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);
    }
}

我还没有进行过广泛的测试,所以使用风险自负.

.net相关问答推荐

无法在 Blazor Server 应用程序中触发 InputRadio 的 onchange 事件

您可以为 Func 或 Action 类型的函数或子参数指定默认值吗?

每当属性值发生变化时引发事件?

单线程单元 - 无法实例化 ActiveX 控件

如何创建 LINQ to SQL 事务?

序列化私有成员数据

C# 中的 myCustomer.GetType() 和 typeof(Customer) 有什么区别?

将跟踪输出重定向到控制台

是否可以更改 Winforms 组合框以禁用输入?

ASP.NET Core (.NET Core) 和 ASP.NET Core (.NET Framework) 的区别

如何从 XDocument 获取 Xml 作为字符串?

mscorlib 代表什么?

如何在 WebBrowser 控件中注入 Javascript?

beforefieldinit 标志有什么作用?

将两个列表映射到 C# 中的字典中

我应该如何删除 DbSet 中的所有元素?

确定使用 ContextMenuStrip 的控件

记录器包装器最佳实践

WPF 中的 Application.DoEvents() 在哪里?

在类型 c# 上切换大小写