徐驰

导航

c# 更换桌面壁纸

  public class WinAPI
    {
        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
    }

 

   private void changeImg()
        {
            string bmpPath = @"C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\Wallpaper1.bmp";//新图片要存储的位置
            publicClass pc = new publicClass();
            string ImagePath = pc.getImageSource();//图片路径
            string ImageFormt = ImagePath.Substring(ImagePath.LastIndexOf('.'));//获取图片格式
            pc.changImgSize(pc.ScreenWidth, pc.ScreenHeight, ImagePath).Save(bmpPath, ImageFormat.Bmp);//设置图片格式和大小
            int nResult;
            if (File.Exists(bmpPath))
            {

                nResult = WinAPI.SystemParametersInfo(20, 1, bmpPath, 0x1 | 0x2); //更换壁纸
                if (nResult == 0)
                {
                    MessageBox.Show("没有更新成功!");
                }
                else
                {
                    RegistryKey hk = Registry.CurrentUser;
                    RegistryKey run = hk.CreateSubKey(@"Control Panel\Desktop\");
                    run.SetValue("Wallpaper", bmpPath);  //将新图片路径写入注册表
                    //MessageBox.Show("更新成功");
                }
            }
            else
            {
                MessageBox.Show("文件不存在!");
            }
        }

 

上面是代码,下面加下来对上面的代码加以说明:

   首先,能够成为壁纸的图片必须格式为bmp的图片,所以在更换前要进行判断是否为 bmp格式图片若不是得 转化格式

   其次,准备好了图片,就要将已壁纸的形式显示了,要实现这个功能要用到 “user32.dll”这个链接库了,他是Windows用户界面相关应用程序接口,用于包括Windows处理,基本用户界面等特性,如创建窗口和发送消息。

 

  在早期32-bit 版本的Windows中,用户控件是在ComCtl32中实现的,但是一些控件的显示功能是在User32.dll中实现的。例如在一个窗口中非客户区域(边框和菜单)的绘制就是由User32.dll来完成的。User32.dll 是操作系统的一个核心控件,它和操作系统是紧密联系在一起的。也就是说,不同版本的Windows中User32.dll 是不同。因此,应用程序在不同版本的Windows中运行的时候,由于User32.dll的不同,会导致应用程序的界面通常会有微小的不同

通过查找帮助文档其中 函数“SystemParametersInfo” 是用来处理壁纸的 呵呵  。。。通过  [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]引用吧。

实现函数后你就可以发现了壁纸已经更换成了 你想要的图片了。不过不要高兴太早,这时的图片还没成为真正的背景 。

最后一步  将修改的后的图片注册到注册表中 

可以通过 cmd——regedit——HKEY-Users——。DEFAULT——Control Panel——Desktop——Wallpaper  查看是否将墙纸注册为新图片的存储路径。如果不经过这一步那么重启电脑后,壁纸将是蓝色 无背景状态。

posted on 2011-12-26 18:27  徐驰  阅读(1817)  评论(0编辑  收藏  举报