目的:下载cn.bing.com或http://www.bing.com/的背景图片,并将其设为壁纸
思路:根据用户输入的地址,首先下载对应网址的页面并解析其中的图片地址。接着下载图片,调用系统api将其设为壁纸。其中的下载都使用socket来实现http的get请求。
出现的问题和困难之处:
- http://www.bing.com/对于没有包含特定cookie的请求会将其重定向到cn.bing.com。
- 找到图片的地址
- 如何设定其为壁纸
解决方法:
- 在get命令中添加cookie值
- 使用了string的find函数(可能更好的是正则表达式吧)
- 使用IActiveDesktop的SetWallpaper方法(第一个参数需要时宽字符的字符串,com编程相关?)
相关代码:
Code
1#include <WinInet.h>//需在下面.h之前
2#include <shlobj.h>
3
4//char to wchar
5wchar_t *charToW(const char *str)
6{
7 int nc = strlen(str);
8 int n = (size_t)MultiByteToWideChar(CP_ACP, 0, str, nc, NULL, 0);
9 wchar_t *re = NULL;
10 re = new wchar_t[n + 1];
11 if(NULL != re)
12 {
13 MultiByteToWideChar(CP_ACP, 0, str, nc, re, n);
14 re[n] = 0;
15 }
16 return re;
17}
18
19//设置壁纸
20bool changeWallPaper(const char *pic)
21{
22 wchar_t *w = charToW(pic);
23 //SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, w, SPIF_UPDATEINIFILE);
24 HRESULT hr;
25 IActiveDesktop *desk;
26 CoInitialize(NULL);
27 hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER, IID_IActiveDesktop, (void **)&desk);
28 if (S_OK == hr)
29 {
30 WALLPAPEROPT opt;
31 opt.dwSize = sizeof(WALLPAPEROPT);
32 opt.dwStyle = WPSTYLE_STRETCH;
33 desk->SetWallpaper(w, 0);
34 desk->SetWallpaperOptions(&opt, 0);
35 desk->ApplyChanges(AD_APPLY_ALL);
36 desk->Release();
37 }
38 CoUninitialize();
39 if(NULL != w) delete[] w;
40 return true;
41}
42
1#include <WinInet.h>//需在下面.h之前
2#include <shlobj.h>
3
4//char to wchar
5wchar_t *charToW(const char *str)
6{
7 int nc = strlen(str);
8 int n = (size_t)MultiByteToWideChar(CP_ACP, 0, str, nc, NULL, 0);
9 wchar_t *re = NULL;
10 re = new wchar_t[n + 1];
11 if(NULL != re)
12 {
13 MultiByteToWideChar(CP_ACP, 0, str, nc, re, n);
14 re[n] = 0;
15 }
16 return re;
17}
18
19//设置壁纸
20bool changeWallPaper(const char *pic)
21{
22 wchar_t *w = charToW(pic);
23 //SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, w, SPIF_UPDATEINIFILE);
24 HRESULT hr;
25 IActiveDesktop *desk;
26 CoInitialize(NULL);
27 hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER, IID_IActiveDesktop, (void **)&desk);
28 if (S_OK == hr)
29 {
30 WALLPAPEROPT opt;
31 opt.dwSize = sizeof(WALLPAPEROPT);
32 opt.dwStyle = WPSTYLE_STRETCH;
33 desk->SetWallpaper(w, 0);
34 desk->SetWallpaperOptions(&opt, 0);
35 desk->ApplyChanges(AD_APPLY_ALL);
36 desk->Release();
37 }
38 CoUninitialize();
39 if(NULL != w) delete[] w;
40 return true;
41}
42
使用方法:
在命令行下直接敲入命令(下载http://www.bing.com/的壁纸)或者 “命令 cn.bing.com” 来下载cn.bing.com的壁纸
下载地址:changewallpaper