`
liusu
  • 浏览: 169845 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

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

    博客分类:
  • Life
阅读更多
最近发现 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文件和源码。
1
0
分享到:
评论
6 楼 不顾一切的自由 2012-10-24  
谢谢,这东西以前在学校学过,现在一点也不会用。
5 楼 liusu 2012-10-20  
不顾一切的自由 写道
显示的效果是这样的


怎么解决呢?

实在不好意思。 这个东西是我有段时间想体会一下C#的编程方式,临时写的。 可能现在跑已经有点问题了。。。 不过等我有时间,我会看看。
4 楼 不顾一切的自由 2012-10-10  
显示的效果是这样的


怎么解决呢?
3 楼 不顾一切的自由 2012-10-10  
我怎么运行不了呢?一打开就停止。
2 楼 红色蒲公英lazyboy 2011-07-31  
怎么用
1 楼 lyonslee 2010-08-04  
用了一下,很好用,不错!

相关推荐

Global site tag (gtag.js) - Google Analytics