聽說你不會用代碼換壁紙?
文章來自公衆號【狗子的圈】
聽說你每天爲了找到一張好看到 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。就可以完成代碼換壁紙的操作了。
有圖有真相