65.9K
CodeProject 正在变化。 阅读更多。
Home

C# 壁纸切换器

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (1投票)

2007 年 11 月 29 日

CPOL

1分钟阅读

viewsIcon

48448

downloadIcon

698

Windows 服务代码,可在设定的时间间隔更改壁纸。

引言

这是一个简单的 Windows 服务,它会按照配置的间隔切换壁纸。

背景

这篇文章的目的是让我的/你的空闲时间变得更有用。

Using the Code

此 Windows 服务的 start() 方法执行配置并启动计时器。 ConfigReader 类用于读取包含在附加 zip 文件中的 XML 文件。

public void Start()
{
//Get the config file path
configPath = Assembly.GetExecutingAssembly().Location;
int i = configPath.LastIndexOf("\\");
configPath = configPath.Substring(0, i) + "\\AppConfig.xml";

// Create, configure & Start timer 
t = new Timer(1000 * double.Parse(WallpaperChanger.ConfigReader.GetConfigValue
    (configPath, "TimerIntervalSeconds")));
t.Elapsed += new ElapsedEventHandler(t_Elapsed);

//Get the image files in an array
arrFiles = System.IO.Directory.GetFiles(WallpaperChanger.ConfigReader.GetConfigValue
    (configPath, "WallpaperDirectory"), "*.bmp", 
    System.IO.SearchOption.AllDirectories);
t.Start();
}

Assembly.GetExecutingAssembly().Location 会给出当前程序集的路径。AppConfig.xml 配置文件包含间隔和壁纸目录。此 AppConfig.xml 应该与 EXE 文件位于同一目录中。

t = new Timer(1000 * double.Parse
    (WallpaperChanger.ConfigReader.GetConfigValue(configPath, "TimerIntervalSeconds")));

这行代码使用从 AppConfig.xml 配置的间隔初始化计时器。

t.Elapsed += new ElapsedEventHandler(t_Elapsed);

创建一个 Elapsed 事件的处理程序将在每个间隔被触发

arrFiles = System.IO.Directory.GetFiles(WallpaperChanger.ConfigReader.GetConfigValue
    (configPath, "WallpaperDirectory"), "*.bmp", System.IO.SearchOption.AllDirectories);

这行代码获取目录中所有 BMP 图像文件的完整路径,该目录在 AppConfig.xml 中配置。

t.Start(); 启动计时器。

t_Elapsed() 方法将根据配置的定期间隔被调用。此函数执行本文标题所述的主要任务。

void t_Elapsed(object sender, ElapsedEventArgs e)
{
//Set the wallpaper based on global variable currentIndex
if (currentIndex < arrFiles.Length)
{
WinAPI.SystemParametersInfo(WinAPI.SPI_SETDESKWALLPAPER, 1, 
    arrFiles[currentIndex], WinAPI.SPIF_SENDCHANGE);
currentIndex++;
}
else
{
currentIndex = 0;
}
}

WINAPI 类如下所示

public class WinAPI
{
[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;
} 

以下系统调用使用 arrFiles[currentIndex] 中给定的图像文件设置桌面。

WinAPI.SystemParametersInfo(WinAPI.SPI_SETDESKWALLPAPER, 1, 
    arrFiles[currentIndex], WinAPI.SPIF_SENDCHANGE);

关注点

这旨在让你微笑。如果它没有,那么这篇文章不适合你。

历史

  • 2007 年 11 月 28 日:初始发布
© . All rights reserved.