美丽桌面墙纸自动换

介绍
本文介绍使用C#编写如何在指定的时间内自动更换已经指定的墙纸。运行代码示例需要.net 2.0 以上版本支持。运行程序后将显示在系统托盘内。双击可打开配置主窗体。你可以添加或删除图片,还可以设置墙纸更换的时间。




示例
设置桌面图片

设置桌面的图片我们需要用到WINAPI SystemParametersInfo才可以完成:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SystemParametersInfo(
                        int uAction, int uParam,
                        string lpvParam, int fuWinIni);
public const int SPI_SETDESKWALLPAPER = 20;
public const int SPIF_SENDCHANGE = 0x2;

...

int result = SystemParametersInfo(SPI_SETDESKWALLPAPER,
                   1, tempImageFilePath, SPIF_SENDCHANGE);

要设置壁纸的比例风格,还必须设置注册表键TileWallpaper WallpaperStyle。它们在注册表的位置是HKEY_CURRENT_USER\Control Panel\Desktop。

Center : TileWallpaper=0, WallpaperStyle=1
Stretch : TileWallpaper=0, WallpaperStyle=2
Tile: TileWallpaper=1, WallpaperStyle=0

使用下面的代码修改注册表:

using Microsoft.Win32;

...

private static void SetRegistryKeyForWallpaper(
                          string keyName, string value)
{
   RegistryKey deskTopKey =
       Registry.CurrentUser.OpenSubKey(
              @"Control Panel\Desktop", true);
   deskTopKey.SetValue(keyName, value);
}

添加BestFit样式
我们添加了一种墙纸填充的风格BestFit。这种风格尺度比例的图像,使图像不歪斜。周围的图像的部分可能是空白,这个区域的颜色可以选择。

private static void ConvertSourceFileToBmp(
          string sourceFilePath, string tempBmpFilePath,
          ScaleStyles scaleStyle, Color backColor)
{
    Image sourceImg = Image.FromFile(sourceFilePath);
    if (scaleStyle != ScaleStyles.BestFit)
    {
        sourceImg.Save(tempBmpFilePath,
             System.Drawing.Imaging.ImageFormat.Bmp);
    }
    else
    {
        //get the dimensions of the screen
        float H =
          System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
        float W =
          System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;

        //get the image dimensions
        float h = sourceImg.Height;
        float w = sourceImg.Width;

        //dimensions of target
        float targetHeight = -1;
        float targetWidth = -1;

        //find the appropriate height and width
        if (H / h >= W / w)
        {
            targetWidth = w;
        }
        else
        {
            targetHeight = h;
        }
        if (targetHeight == -1)
        {
            targetHeight = (H / W) * targetWidth;
        }
        if (targetWidth == -1)
        {
            targetWidth = (W / H) * targetHeight;
        }

        //create a new image with the default back color
        //with the scaled dimensions w.r.t. image and screen
        Bitmap bmpImage = new Bitmap((int)targetWidth,
                                         (int)targetHeight);
        Graphics g = Graphics.FromImage(bmpImage);
        SolidBrush backgroundColorBrush =
                                  new SolidBrush(backColor);
        g.FillRectangle(backgroundColorBrush, 0, 0,
                           bmpImage.Width, bmpImage.Height);
       
        //layout this image in the center
        g.DrawImage(sourceImg,
               Math.Abs(targetWidth-sourceImg.Width)/2,
               Math.Abs(targetHeight - sourceImg.Height)/2,
               sourceImg.Width, sourceImg.Height);

        //save it as bmp
        bmpImage.Save(tempBmpFilePath,
                   System.Drawing.Imaging.ImageFormat.Bmp);

        //dispose stuff
        backgroundColorBrush.Dispose();
        g.Dispose();
    }
}

载入扩展资源
为我们的主程序添加icon图标。当墙纸被改变后系统托盘图标也随之改变。

ApplicationIcon = Icon.ExtractAssociatedIcon("App.ico");

如果你不想因为程序被复制使用的时候,未复制走ico图标图片而使程序运行失败,可以将ico图片打包到程序的资源中,这样ico图片将编译在exe文件中。步骤如下:

  •  为项目添加资源文件
  •  重命名你想要的资源文件(例如:Resource1.resx)
  •  打开资源文件,添加icons。
  •  在代码中使用嵌入的资源,使用ResourceManager类。

ResourceManager resourceManager =
    new ResourceManager("WallpaperChanger.Resource1",
                       Assembly.GetExecutingAssembly());

资源文件的名称是由项目的默认命名控件和资源文件名称组合而成的。可以使用名称获取想要的资源:

ResourceManager resourceManager =
   new ResourceManager("WallpaperChanger.Resource1",
                        Assembly.GetExecutingAssembly());
ApplicationIcon = (Icon)resourceManager.GetObject("App");
WallpaperCurrentlyChangingIcon =
           (Icon)resourceManager.GetObject("Changing");


添加托盘图标
 

this.notifyIcon = new NotifyIcon();
this.notifyIcon.Text = "Wallpaper Changer";
this.notifyIcon.Icon = NotifyIconManager.ApplicationIcon;
this.notifyIcon.Visible = true;
this.notifyIcon.ShowBalloonTip(1, "Started " +
   NotifyIconManager.APP_TITLE, "You can double click on this icon to
   configure settings and choose pictures.", ToolTipIcon.Info);
this.notifyIcon.DoubleClick +=
                new EventHandler(this.configureMenuItem_Click);

定期更换墙纸

使用定时器

//create timer and set time interval
this.periodicTimer = new Timer();
this.periodicTimer.Interval =
  Int32.Parse(this.optionsDictionary["TimeIntervalInSeconds"])*1000;
this.periodicTimer.Tick += new EventHandler(periodicTimer_Tick);
this.periodicTimer.Start();

随机抽取文件设置设置墙纸

private void periodicTimer_Tick(object sender, EventArgs e)
{
    this.periodicTimer.Stop();

    try
    {
        int failCount = 0;
       
        while (failCount < 3)
        {
            ImageInfo nextFileImageInfo =
                     this.GetNextRandomImageFileInfo();   
            //if file is not present then try again
            if (nextFileImageInfo == null ||
                   !File.Exists(nextFileImageInfo.FilePath))
            {
                failCount++;
                continue;
            }
            else
            {
                this.SetAsWallpaperNow(nextFileImageInfo);
                break;
            }
        }
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show("Error! " + ex.Message +
             "\r\n" + ex.StackTrace);
    }

    this.periodicTimer.Start();
}

代码下载

WallpaperChanger_src.zip

参考资料
翻译参考 http://www.codeproject.com/KB/cs/wallpaperchanger.aspx
关于托盘图标NotifyIcon知识  http://dev.mjxy.cn/a-Tray-icon-NotifyIcon.aspx

填写您的邮件地址,订阅我们的精彩内容:

posted @ 2011-08-15 11:08  敏捷学院  阅读(3662)  评论(0编辑  收藏  举报