网上有很多用其它语言来设置桌面壁纸的方法,但是我没有找到用C#语言来写的,由于自己需要在项目中做这样一个功能,所以通过察看其它语言写的资料来自己用C#写了一个这样的程序。
主要是同过WINDOWS API函数来设置壁纸,然后还要通过写注册表来设置壁纸的显示方式(中心、平铺、拉伸)。
注意事项:首先,如果要设置壁纸后立即出现中心、平铺或拉伸的效果,就要先设置壁纸的显示方式,再设置壁纸;其次,为了在桌面属性里看到壁纸,并且避免重启后壁纸消失。那么就应该把位图(设置壁纸需要是位图格式)保存到一个目录,然后把壁纸路径设为这个路径。
在HKEY_USERS/.DEFAULT/Control Panel/DeskTop中,
TileWallpaper WallpaperStyle
居中: 0 0
平铺: 1 0
拉伸: 0 2
添加命名空间:
using System.Runtime.InteropServices; //调用WINDOWS API函数时要用到
using Microsoft.Win32; //写入注册表时要用到
//以中心方式显示墙纸
private void menuItemCenter_Click(object sender, System.EventArgs e)
...{
//设置墙纸显示方式
RegistryKey myRegKey = Registry.CurrentUser.OpenSubKey("Control Panel/desktop",true);
//赋值
//注意:在把数值型的数据赋到注册表里面的时候,
//如果不加引号,则该键值会成为“REG_DWORD”型;
//如果加上引号,则该键值会成为“REG_SZ”型。
myRegKey.SetValue("TileWallpaper","0");
myRegKey.SetValue("WallpaperStyle","0");
//关闭该项,并将改动保存到磁盘
myRegKey.Close();
//设置墙纸
Bitmap bmpWallpaper = (Bitmap)pictureBox1.Image;
bmpWallpaper.Save("resource.bmp",ImageFormat.Bmp); //图片保存路径为相对路径,保存在程序的目录下
string strSavePath = Application.StartupPath + "/resource.bmp";
SystemParametersInfo(20,1,strSavePath,1);
}
//以平铺方式显示墙纸
private void menuItemTile_Click(object sender, System.EventArgs e)
...{
//设置墙纸显示方式
RegistryKey myRegKey = Registry.CurrentUser.OpenSubKey("Control Panel/desktop",true);
myRegKey.SetValue("TileWallpaper","1");
myRegKey.SetValue("WallpaperStyle","0");
myRegKey.Close();
//设置墙纸
Bitmap bmpWallpaper = (Bitmap)pictureBox1.Image;
bmpWallpaper.Save("resource.bmp",ImageFormat.Bmp); //图片保存路径为相对路径,保存在程序的目录下
string strSavePath = Application.StartupPath + "/resource.bmp";
SystemParametersInfo(20,1,strSavePath,1);
}
//以拉伸方式显示墙纸
private void menuItemStretch_Click(object sender, System.EventArgs e)
...{
//设置墙纸显示方式
RegistryKey myRegKey = Registry.CurrentUser.OpenSubKey("Control Panel/desktop",true);
myRegKey.SetValue("TileWallpaper","0");
myRegKey.SetValue("WallpaperStyle","2");
myRegKey.Close();
//设置墙纸
Bitmap bmpWallpaper = (Bitmap)pictureBox1.Image;
bmpWallpaper.Save("resource.bmp",ImageFormat.Bmp); //图片保存路径为相对路径,保存在程序的目录下
string strSavePath = Application.StartupPath + "/resource.bmp";
SystemParametersInfo(20,1,strSavePath,1);
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sonyicn/archive/2006/05/20/746280.aspx
【以下是我(sqzxcv)在学习中发现的问题,仅作参考,如有异议,欢迎指出...】
我看了这篇文章后,就照着做了一篇,发现不行还是有问题,仔细看看发现帖主似乎遗漏了一下都是。。。。。
1.在注册表中设置TileWallpaper,WallpaperStyle的同时,还要将壁纸的路径写到同目录下的Wallpaper里面去。
2.上面HKEY_USERS/.DEFAULT/Control Panel/DeskTop改为HKEY_CURRENT_USERS/Control Panel/DeskTop.
我用的是XP sp3系统。