使用 C# 实现Windows桌面壁纸软件

一、设置Windows壁纸

将电脑上的图片设置为壁纸,代码如下:

csharp 复制代码
[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 = 0x1;

public void SetWallpaper(string path)
{
    try
    {
        if (!File.Exists(path))
        {
            return;
        }
        FileLogger.Info($"set wallpaper: {path}");
        SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE);
    }
    catch (Exception ex)
    {
        FileLogger.Error(ex.ToString());
    }
}

二、随机给windows设置一张壁纸

这里推荐一个接口,可以获取到Bing壁纸:

https://api.vvhan.com/api/bing?type=json //获取今日壁纸
https://api.vvhan.com/api/bing?type=json&rand=sj //获取随机壁纸

返回结果如下:

{
  "success": true,
  "data": {
    "date": 20240623,
    "title": "达卡环形交叉路口的鸟瞰图,孟加拉国 (© Azim Khan Ronnie/Amazing Aerial Agency)",
    "url": "https://cn.bing.com/th?id=OHR.DhakaBangladesh_ZH-CN6777866162_1920x1080.jpg"
  }
}

之后将图片下载下来,使用上文中的方法就可以实现随机设置一张壁纸的功能了

从URL下载图片的方法如下:

csharp 复制代码
public bool SavePhotoFromUrl(string fileName, string url)
{
    bool value = false;
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        WebResponse response = request.GetResponse();
        Stream stream = response.GetResponseStream();
        if (!response.ContentType.ToLower().StartsWith("text/"))
        {
            value = SaveBinaryFile(response, fileName);
        }
    }
    catch (Exception err)
    {
        FileLogger.Error(err.ToString());
    }
    return value;
}
private bool SaveBinaryFile(WebResponse response, string FileName)
{
    bool Value = true;
    byte[] buffer = new byte[1024];

    try
    {
        if (File.Exists(FileName))
            File.Delete(FileName);
        Stream outStream = System.IO.File.Create(FileName);
        Stream inStream = response.GetResponseStream();

        int l;
        do
        {
            l = inStream.Read(buffer, 0, buffer.Length);
            if (l > 0)
                outStream.Write(buffer, 0, l);
        }
        while (l > 0);

        outStream.Close();
        inStream.Close();
    }
    catch
    {
        Value = false;
    }
    return Value;
}

我自己开发了一个随机壁纸小软件,免费无毒无广,欢迎下载使用

相关推荐
2501_9032386522 分钟前
Git Bash:Windows下的强大命令行工具
windows·git·bash·个人开发
Joey_friends40 分钟前
【Linux】线程详解
开发语言
_GR1 小时前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
Good Note1 小时前
Golang——常用库context和runtime
开发语言·爬虫·golang
吃汤圆的抹香鲸1 小时前
GoLand 安装包 绿色版 Win,Mac,Linux 包含IntelliJ全家桶 专为Go语言设计的集成开发环境(IDE)
linux·windows·macos·go·intellij-idea·go1.19
清河__1 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang
张声录12 小时前
国密算法Sm2工具类--golang实现版
开发语言·后端·golang
吃汤圆的抹香鲸2 小时前
Rider 安装包 绿色版 Win/Mac/Linux 适合.NET和游戏开发者使用 2025全栈开发终极指南:从零配置到企业级实战
linux·运维·windows·sql·游戏·macos·.net
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
HH牛码2 小时前
C#学生管理系统 进阶(通过接口,继承接口的类,实现接口约束_对List中存储的数据进行排列)
c#