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;
}
}
C#电脑背景图片Bing