问题
I wish to set a wallpaper for Windows 7 using a C# service. This is working fine when the service is run as a console application. But after installing the service and starting it, then it does not switch between wallpapers. Anybody have an idea how to set the wallpaper inside the window service?
Here is my code:
private String file = @"C://Users//Alvin//Pictures//onepiece.jpg";
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
SetWallpaper(file, 0);
}
private void SetWallpaper(string WallpaperLocation, int WallpaperStyle)
{
try
{
// Sets the actual wallpaper
SystemParametersInfo(20, 0, "@" + WallpaperLocation, 0x01 | 0x02);
// Set the wallpaper style to streched (can be changed to tile, center, maintain aspect ratio, etc.
RegistryKey rkWallPaper = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
// Sets the wallpaper style
switch (walpaperStyle)
{
case 0:
rkWallPaper.SetValue(@"WallpaperStyle", "0");
rkWallPaper.SetValue(@"TileWallpaper", "1");
break;
case 1:
rkWallPaper.SetValue(@"WallpaperStyle", "0");
rkWallPaper.SetValue(@"TileWallpaper", "0");
break;
case 2:
rkWallPaper.SetValue(@"WallpaperStyle", "2");
rkWallPaper.SetValue(@"TileWallpaper", "0");
break;
case 3: // (Windows 7 and later)
rkWallPaper.SetValue(@"WallpaperStyle", "6");
rkWallPaper.SetValue(@"TileWallpaper", "0");
break;
case 4: // (Windows 7 and later)
rkWallPaper.SetValue(@"WallpaperStyle", "10");
rkWallPaper.SetValue(@"TileWallpaper", "0");
break;
}
rkWallPaper.Close();
cetakService("sukses set walpaper");
}
catch (Exception e)
{
cetakService("Error "+e.Message.ToString());
}
}
回答1:
If you wish to switch the wallpapers from time to time, please note that OnStart() is run once, when the service starts. I dont see how you're changing the wallpaper through SetWallpaper. It actually runs once and sets the wallpaper. No logic is implemented to keep changing the wallpaper for different cases to be executed. This code should change the wallpaper the first time the service starts, if that's what you wish to do, please make sure that your service has sufficient rights to access registry values.
来源:https://stackoverflow.com/questions/20092611/how-to-change-the-wallpaper-using-service-c-sharp