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

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

相关推荐
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说2 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔2 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机