How do I change the screensaver programmatically?

て烟熏妆下的殇ゞ 提交于 2019-12-01 16:11:38

I'll answer my question with the piece of code that worked to me:

public sealed class Screensaver
{
    Screensaver() { }

    const int SPI_SETSCREENSAVEACTIVE = 0x0011;

    [DllImport("user32", CharSet=CharSet.Auto)]
    unsafe public static extern short SystemParametersInfo (int uiAction, int uiParam, int* pvParam, int fWinIni);

    public static void Set(string path)
    {
        try
        {
            RegistryKey oKey = Registry.CurrentUser.OpenSubKey("Control Panel",
            true);
            oKey = oKey.OpenSubKey("desktop", true);
            oKey.SetValue("SCRNSAVE.EXE", path);
            oKey.SetValue("ScreenSaveActive", "1");

            unsafe
            {
                int nX = 1;
                SystemParametersInfo(
                SPI_SETSCREENSAVEACTIVE,
                0,
                &nX,
                0
                );
            }
        }
        catch (Exception exc)
        {
            System.Windows.Forms.MessageBox.Show(exc.ToString());
        }
    }
}

Then, when calling it from my application:

static string ResourcePath(string resource)
{
    return Application.StartupPath + "\\Resources\\" + resource;
}

Program.Screensaver.Set(Program.ResourcePath("svr1.scr"));

I read somewhere I should write a name no longer than 8 characters (a bit weird, but XP is all like this), so my screensaver is called svr1.scr (not really object oriented, but does the trick)

This is the command that windows executes when installing a new one

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