public class DesktopService { [DllImport("user32.dll", EntryPoint = "SystemParametersInfoA")] static extern Int32 SystemParametersInfo(Int32 uAction, Int32 uParam, string lpvparam, Int32 fuwinIni); private const string BingUrl = "http://www.bing.com"; private const string BingBasePath = @"E:\BingWallpaper"; private int _idx = -1; private int idx { get => _idx; set { if (value >= 0 && value < 8) _idx = value; } } private static DesktopService _instance = null; public static DesktopService Instance { get { return _instance ?? (_instance = new DesktopService()); } } /// <summary> /// 設置桌面背景圖片 /// </summary> public Task SetDesktopBackground(bool isNext = true) { return Task.Factory.StartNew(() => { if (!Directory.Exists(BingBasePath)) { Directory.CreateDirectory(BingBasePath); } if (isNext) idx++; else idx--; string bingPath = $@"{BingBasePath}\{DateTime.Now.AddDays(-idx).ToString("yyyy-MM-dd")}.bmp"; if (!File.Exists(bingPath)) { var imageUrl = GetImageUrl(); var image = GetImage(imageUrl); image.Save(bingPath, System.Drawing.Imaging.ImageFormat.Bmp); } SystemParametersInfo(20, 0, bingPath, 1); }); } /// <summary> /// 獲取圖片Url /// </summary> /// <returns></returns> private string GetImageUrl() { string InfoUrl = $"http://cn.bing.com/HPImageArchive.aspx?idx={idx}&n=1"; string xmlString = HttpGet(InfoUrl); // 定義正則表達式用來匹配標籤 Regex regImg = new Regex("<Url>(?<imgUrl>.*?)</Url>", RegexOptions.IgnoreCase); // 搜索匹配的字符串 MatchCollection matches = regImg.Matches(xmlString); // 取得匹配項列表 string imageUrl = BingUrl + matches[0].Groups["imgUrl"].Value; return imageUrl; } /// <summary> /// Get請求 /// </summary> /// <param name="url"></param> /// <returns></returns> private string HttpGet(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; string html; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { Stream myResponseStream = response.GetResponseStream(); using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8)) { html = myStreamReader.ReadToEnd(); } } return html; } /// <summary> /// 圖片請求 /// </summary> /// <param name="url">要訪問的圖片所在網址</param> /// <returns></returns> private Image GetImage(string url) { Image img; try { WebRequest request = WebRequest.Create(url); using (WebResponse response = request.GetResponse()) { img = Image.FromStream(response.GetResponseStream()); } } catch { img = null; } return img; } }