听说你不会用代码换壁纸?
文章来自公众号【狗子的圈】
听说你每天为了找到一张好看到 Windows 壁纸而疯狂百度?听说你是个开发但是你不会用代码换壁纸?如果是这样,请往下读。
Step 1 创建应用
新建一个 Console 应用
dotnet new console -o BingWallpaper
此段代码暗藏珠玑。
首先,使用了 dotnet core 开发环境。其次,表明图片来源是 Bing 。
接下来就是花里胡哨的 C# 代码
Step 2 上代码
using System;
using System.Net.Http;
using HtmlAgilityPack;
using System.Threading.Tasks;
using System.Net;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Drawing;
namespace web
{
class Program
{
static void Main(string[] args)
{
var client = new HttpClient();
var html = client.GetStringAsync("https://cn.bing.com").GetAwaiter().GetResult();
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
string str = "//*[@id='bgLink']";
var imgPath = htmlDoc.DocumentNode.SelectSingleNode(str).Attributes["href"].Value;
new WebClient().DownloadFile($"https://cn.bing.com{imgPath}", "bg.jpg");
Image image = Image.FromFile("bg.jpg");
image.Save("bg.bmp",System.Drawing.Imaging.ImageFormat.Bmp);
SystemParametersInfo(20, 0, AppDomain.CurrentDomain.BaseDirectory + "bg.bmp", 1|2);
Console.WriteLine("设置成功");
}
[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern int SystemParametersInfo(
int uAction,
int uParam,
string lpvParam,
int fuWinIni
);
}
}
Step 3 解释一套
首先,我们引入了 nuget 包 HtmlAgilityPack
,这样我们就可以解析爬取到到 HTML 页面。写出如下代码
// 根据 XPATH 找到指定节点的值
string str = "//*[@id='bgLink']";
var imgPath = htmlDoc.DocumentNode.SelectSingleNode(str).Attributes["href"].Value;
这样我们就得到了 Bing 首页背景图的 URL。
接下来,当然就是把图片 窃 到本地
new WebClient().DownloadFile($"https://cn.bing.com{imgPath}", "bg.jpg");
这么一行代码,就把图片窃取成功啦
嘿嘿
最后干嘛?当然是操作啊
把下载到的图片转为 bmp 后,调用 Win32 API 中的方法 SystemParametersInfo。就可以完成代码换壁纸的操作了。
有图有真相