欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自动设置Bing背景作为桌面背景(Win7成功)

程序员文章站 2022-07-12 11:55:37
...
最近发现 http://cn.bing.com 主页每天都会有不同的背景图片,而且都蛮漂亮的。 于是有个想法,写个程序自动将bing站的背景

作为桌面背景。 考虑设置桌面背景这个‘专业’的工作我的本职java语言肯定是实现不了,临时学学C#'来实现。

其中包括,从http下载图片,调用DLL设置桌面背景等操作,一段一段的代码都是从网上搜索的。我只是把这些功能组合了起来。

代码估计会给专业写C#的人笑,但是,管它呢, 贴在这里做个纪念,也给自己以后写c#小程序,做个参考。

源码如下:

/*
 * Created by SharpDevelop.
 * User: hsieh
 * Date: 2009/10/26
 * Time: 21:23
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Web;
using System.Net;

namespace DesktopSwitch
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Download image from 'http://cn.bing.com'.");
			Program dsw = new Program();
			string tempImage = Path.GetTempPath() + "\\" + "bing.jpg";
			dsw.GetImageFromBing(tempImage);
			dsw.SetDestPicture(tempImage);
			//Console.Write("Press any key to continue . . . ");
			//Console.ReadKey(true);
		}
		
		private void GetImageFromBing(String imagePath)
		{
			string url = "http://cn.bing.com";
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
			WebResponse response = request.GetResponse();
			Stream stream = response.GetResponseStream();
			Encoding encode = Encoding.GetEncoding("utf-8");
            StreamReader sr = new StreamReader(stream, encode);
            string html = null;
            char[] readbuffer = new char[256];
            int n = sr.Read(readbuffer, 0, 256);
            while (n > 0)
            {
                string str = new string(readbuffer, 0, n);
                html += str;
                n = sr.Read(readbuffer, 0, 256);
            }
            StreamWriter streamw = File.CreateText(@"C:\test3.txt");
			streamw.WriteLine(html);
			streamw.Close();
			
            //string pattern = "height: 267px; background-image: url\\(\\.+\\); opacity: 1;";
            //url:'\/fd\/hpk2\/Hayden_ZH-CN1124177866.jpg',id:'bgDiv'
			string pattern = @"url:'\\(/fd\\/[\w\d]+\\/[\w\d]+_ZH-CN[\d]{5,}\.jpg)',id:'bgDiv'";
            Match match = Regex.Match(html, pattern);
            if(match.Success)
            {
            	string imageUrl = match.Groups[1].Value;
            	imageUrl = url + imageUrl.Replace("\\","");
            	System.Console.WriteLine("Set image '" + imageUrl + "' as the Desktop background.");
            	downloadImage(imageUrl,imagePath);
            }
            else
            {
            	System.Console.WriteLine("Can't find image.");
            	System.Environment.Exit(-1);
            }
		}
		
		private void downloadImage(String url, String imagePath)
		{
			try{
				WebRequest request = WebRequest.Create(url);
				request.ContentType = "image/jpeg";
				Stream stream = request.GetResponse().GetResponseStream();
				byte[] mbyte = new byte[100000];
 	 			int allmybyte = (int)mbyte.Length;
  			int startmbyte = 0;
  			while(allmybyte>0)
  			{
  				int m = stream.Read(mbyte,startmbyte,allmybyte);
  				if(m==0)
  					break;
  
  				startmbyte+=m;
  				allmybyte-=m;
  			}
  			FileStream fstr = new FileStream(imagePath,FileMode.OpenOrCreate,FileAccess.Write);
  			fstr.Write(mbyte,0,startmbyte);
  			stream.Close();
  			fstr.Close();
			}catch(Exception e){
				Console.WriteLine(e.Message);
				Console.WriteLine("Get image from bing failed. Exit");
				System.Environment.Exit(-1);
			}
			
		}
		
		[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(
            int uAction,
            int uParam,
            string lpvParam,
            int fuWinIni
            );

        /// <summary>
        /// 设置背景图片
         /// </summary>
        /// <param name="picture">图片路径</param>
        private void SetDestPicture(string picture)
        {
            if (File.Exists(picture))
            {
                if (Path.GetExtension(picture).ToLower() != "bmp")
                { 
                    // 其它格式文件先转换为bmp再设置
                    string tempFile = @"C:\test.bmp";
                    Image image = Image.FromFile(picture);
                    image.Save(tempFile, System.Drawing.Imaging.ImageFormat.Bmp);
                    picture = tempFile;
                    setBMPAsDesktop(picture);
                    File.Delete(tempFile);
                }
                else
                {
                	setBMPAsDesktop(picture);
                }
              
            }
        }
        
        /// <summary>
        /// 设置BMP格式的背景图片
        /// </summary>
        /// <param name="bmp">图片路径</param>
        private void setBMPAsDesktop(string bmp)
        {
        	  SystemParametersInfo(20, 0, bmp, 0x2);
        }

	}
}



附件是编译好的exe文件和源码。