使用 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;
}

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

相关推荐
洲覆6 分钟前
缓存异常:缓存穿透、缓存击穿、缓存雪崩
开发语言·数据库·mysql·缓存
逻极34 分钟前
变量与可变性:Rust中的数据绑定
开发语言·后端·rust
三次拒绝王俊凯1 小时前
java求职学习day47
java·开发语言·学习
合作小小程序员小小店1 小时前
基于可视化天气系统demo,基于python+ matplotlib+request爬虫,开发语言python,数据库无,10个可视化界面,需要的可以了联系。
开发语言·爬虫·python·matplotlib
宝桥南山1 小时前
.NET10 - 尝试一下Blazor Web Assembly Standalone App的fingerprint新特性
microsoft·微软·c#·asp.net·.net·.netcore
一匹电信狗1 小时前
【牛客CM11】链表分割
c语言·开发语言·数据结构·c++·算法·leetcode·stl
2501_938963962 小时前
解析 Lua 虚拟机整数与浮解析 Lua 虚拟机整数与浮点数处理:类型转换与运算精度控制
开发语言·lua
不染尘.2 小时前
图的邻接矩阵实现以及遍历
开发语言·数据结构·vscode·算法·深度优先
国服第二切图仔2 小时前
Rust开发之Trait作为参数与返回值使用
开发语言·后端·rust
千里马学框架2 小时前
windows系统上aosp15上winscope离线html如何使用?
android·windows·html·framework·安卓窗口系统·winscope