C# 通过搜狐微博api远程更换壁纸

通过搜狐微博的api,使用http basic 认证,新浪的oauth还要通过浏览器认证,太麻烦,整个程序分为几个小部分,不难。

实现以下功能:

1,开机启动。程序运行有会创建C:\bgimg文件夹,会将程序自己copy到该文件夹下,以后开机启动将用该文件夹下的程序。下载的壁纸也在该文件夹下。

2,自动更新壁纸。

3,从搜狐微博获取图片链接,下载图片。

4,md5验证,用于比较当前的壁纸与下载的壁纸是否相同。

5,隐藏窗口,后台运行,不需要窗口滴。

6,图片格式转换,xp系统下调用SystemParametersInfo更改壁纸,只支持bmp格式的。这里注意,上传的图片也要是bmp格式的。

代码中用到了搜狐微博提供的封装好的C#.net类,使用很简单。该类库下载地址:

http://www.iiidown.com/source_link.php?type=1&key=71510353&url=http%3A%2F%2Fdlwt.csdn.net%2Ffd.php%3Fi%3D751826827284012%26s%3D025045b263981a9e346d83067b6b9d3c

下面贴上代码:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net; 
using System.Drawing.Imaging;
using
web.ApiService; //搜狐api类库。

namespace client_souhu
{
public partial class main : Form
{
[DllImport(
"user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern int SystemParametersInfo1(
int uAction,
int uParam,
string lpvParam,
int fuWinIni
);
[DllImport(
"user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SystemParametersInfo(uint uAction, uint uParam, StringBuilder lpvParam, uint init);
const uint SPI_GETDESKWALLPAPER = 0x0073;

string localPath = @"c:\bgimg\"; //创建文件夹的路径。
string localFilename = "1.bmp"; //下载下来图片的文件名。
string mainName = "wallpaper.exe"; //主程序的名字。
string lastThemesPaperMd5 = ""; //保存最近一次图片的md5。这里实现有问题,可以不用管先。
string lastBgimgPaperMd5 = ""; //最近上一次下载图片的md5.
string tmpFileName="1.jpg";
bool downloadingImg = false; //该值为true时表示正在下载图片,暂停切换壁纸。
string weiboCreateTime; //微博的创建时间,用于判断图片微博是否更新,从而判断是否要下载图片。
//搜狐微博账号信息。
//在微博上传图片时,微博的内容为imgBz内容,程序根据这个标志,下载图片。对于xp用户,上传的图片必须为.bmp格式的。
//只要在最近20条微博中,有带有imgBz标志的图片微博,就可以更换壁纸
string username = "你的微博账号";
string passwd = "你的微博密码";
string imgBz = "wp_public"; //不同的人用不同的标志,下载不同的图片,该标志自定义

public main()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
updateSelf();
autoRun();
//单独线程。
Thread updateImgThread = new Thread(new ThreadStart(updateImg));
updateImgThread.Start();
Thread downloadImgThread
= new Thread(new ThreadStart(downloadImg));
downloadImgThread.Start();
}


//更新图片
private void updateImg()
{
Thread.CurrentThread.IsBackground
= true;
StringBuilder wallPaperPath
= new StringBuilder(200);
SystemParametersInfo(SPI_GETDESKWALLPAPER,
200, wallPaperPath, 0);
while (true)
{
if (File.Exists(localPath + localFilename) && !downloadingImg)
{
string x = getMD5Hash(wallPaperPath.ToString());
string y = getMD5Hash(localPath + localFilename);
if (x != lastThemesPaperMd5 || y != lastBgimgPaperMd5)
{
SystemParametersInfo1(
20, 0, localPath + localFilename, 1);
lastThemesPaperMd5
= x;
lastBgimgPaperMd5
=y;
//MessageBox.Show("change Paper:Themes");
}
}
Thread.Sleep(
5000);
}
}

//从微博下载图片。
private void downloadImg()
{
Thread.CurrentThread.IsBackground
= true;
WebClient wc
= new WebClient();
while (true)
{
try
{
List
<Status> getInfo = ApiService.FriendsTimeline(username,passwd, 1);
Status firstImg
= getInfo.Find(text=>
{
if (text.text.ToLower() == imgBz.ToLower())
{
return true;
}
return false;
}
);
if (firstImg!=null && firstImg.created_at.ToString() != weiboCreateTime || !File.Exists(localPath + localFilename))
{
downloadingImg
= true;
string imgUrl = firstImg.original_pic;
wc.DownloadFile(imgUrl, localPath
+ tmpFileName);
formatImg(localPath
+ tmpFileName);
weiboCreateTime
= firstImg.created_at.ToString();
wc.Dispose();
File.Delete(localPath
+ tmpFileName);
downloadingImg
= false;
}
}
catch (Exception ex)
{
//MessageBox.Show("downloadImg()"+ex.Message);
}
Thread.Sleep(
30000);
}
}

//设置开机自启动。
private void autoRun()
{
string path = localPath + mainName;
Microsoft.Win32.RegistryKey rk
= Microsoft.Win32.Registry.CurrentUser;
Microsoft.Win32.RegistryKey rk2
= rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.SetValue(
"MyPaper", path);
rk2.Close();
rk.Close();
}

//获取文件md5.
private string getMD5Hash(string pathName)
{
string strResult = "";
string strHashData = "";
byte[] arrbytHashValue;
System.IO.FileStream oFileStream
= null;
System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher
= new System.Security.Cryptography.MD5CryptoServiceProvider();
try
{
oFileStream
= new System.IO.FileStream(pathName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
arrbytHashValue
= oMD5Hasher.ComputeHash(oFileStream);//计算指定Stream 对象的哈希值
oFileStream.Close();
//由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”
strHashData = System.BitConverter.ToString(arrbytHashValue);
//替换-
strHashData = strHashData.Replace("-", "");
strResult
= strHashData;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
return strResult;
}

//更新程序。
private void updateSelf()
{
DirectoryInfo di
= new DirectoryInfo(localPath);
if (!di.Exists)
{
di.Create();
}

try
{
if (Application.ExecutablePath != localPath +mainName)
{
File.Copy(Application.ExecutablePath, localPath
+ mainName, true); //更新文件。
}
}
catch (Exception ex)
{
//
}
}

//隐藏窗口
private bool windowCreate = true;
protected override void OnActivated(EventArgs e)
{
if (windowCreate)
{
base.Visible = false;
windowCreate
= false;
}
base.OnActivated(e);
}

//转换图片为bmp格式。
private void formatImg(string file)
{
using (StreamReader sr = new StreamReader(file))
{
Stream streamReceive
= sr.BaseStream;
Image img
= new Bitmap(streamReceive);
//System.Drawing.Bitmap bmp = new Bitmap(img.Size.Width, img.Size.Height, img.PixelFormat);
System.Drawing.Bitmap bmp;
if (file.ToLower().EndsWith(".gif"))
{
bmp
= new Bitmap(img.Size.Width, img.Size.Height, PixelFormat.Format24bppRgb);
}
else
{
bmp
= new Bitmap(img.Size.Width, img.Size.Height, img.PixelFormat);
}
bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);
System.Drawing.Graphics g
= System.Drawing.Graphics.FromImage(bmp);
g.DrawImage(img,
0, 0);
g.Flush();

g.Save();
g.Dispose();
try
{
bmp.Save(file.ToLower().Replace(
".jpg", ".bmp").Replace(".jpeg", ".bmp").Replace(".gif", ".bmp").Replace(".png", ".bmp"), System.Drawing.Imaging.ImageFormat.Bmp);
}
catch (Exception ex)
{
}
finally
{
img.Dispose();
}
}
}
}
}
有什么错误和不足,请指出,共同学习!
原文地址:https://www.cnblogs.com/fmnisme/p/2058130.html