如何以编程方式更改屏幕保护程序? [英] How do I change the screensaver programmatically?

查看:35
本文介绍了如何以编程方式更改屏幕保护程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 C# 将当前屏幕保护程序更改为自定义屏幕保护程序(我之前在 Visual Studio 中作为资源加载).那怎么可能呢?我已经在 Google 和 SO 上寻找过它,但它们都在谈论如何创建屏幕保护程序",而不是如何更改屏幕保护程序".如果可能,它应该适用于 WinXP、Vista 和 7.

I'd like to change the current Screensaver for a custom one (which I previously loaded as a resource in Visual Studio) using C#. How could that be done? I've looked for it on Google and SO, but it all talks about "How to create a Screensaver", not "How to change a Screensaver". If possible, it should work on WinXP, Vista and 7.

推荐答案

我会用对我有用的一段代码来回答我的问题:

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"));

我在某处读到我应该写一个不超过 8 个字符的名字(有点奇怪,但 XP 都是这样的),所以我的屏幕保护程序被称为 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)

这篇关于如何以编程方式更改屏幕保护程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆