how to change the wallpaper using service c#

99封情书 提交于 2019-12-25 04:59:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!