C# Windows 服务需要修改注册表

标签 c# windows-services registry

我有一项服务需要每 5 分钟更新一次注册表(抵消 gpo)。该代码在常规应用程序中运行良好,但当我将其放入 Windows 服务时,它不会进行更改。我正在为该服务使用本地系统帐户,它没有抛出任何异常

下面的代码在常规控制台应用程序中有效,但在服务中无效:

RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
        if (key != null)
        {
            key.SetValue("ScreenSaverIsSecure", "0", RegistryValueKind.String);
            key.SetValue("ScreenSaveActive", "0", RegistryValueKind.String);
            key.SetValue("ScreenSaveTimeOut", "0", RegistryValueKind.String);
            key.SetValue("SCRNSAVE.EXE", "", RegistryValueKind.String);
        }


        key = Registry.CurrentUser.OpenSubKey(@"Software\Policies\Microsoft\Windows\Control Panel\Desktop", true);
        if (key != null)
        {
            key.SetValue("ScreenSaverIsSecure", "0", RegistryValueKind.String);
            key.SetValue("ScreenSaveActive", "0", RegistryValueKind.String);
            key.SetValue("ScreenSaveTimeOut", "0", RegistryValueKind.String);
            key.SetValue("SCRNSAVE.EXE", "", RegistryValueKind.String);
        }
        System.Diagnostics.Process.Start(@"c:\windows\System32\RUNDLL32.EXE", "user32.dll, UpdatePerUserSystemParameters");

有什么想法吗?

编辑:

感谢您的回复。我不知道为什么“CurrentUser”没有引起我的注意。感谢您指出这一点。

我的问题仍然是针对当前用户推送组策略。现在我正在考虑只创建一个在启动时加载并保持事件状态的应用程序。欢迎任何其他建议。

编辑:

关于 Will 的评论,我无法在 win32 api 中找到 UpdatePerUserSystemParameters 函数签名。这是否意味着它可以不带参数调用?

   [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool UpdatePerUserSystemParameters();

最佳答案

参见 this page :

A service that runs in the context of the LocalSystem account inherits the security context of the SCM...This has several implications:

The registry key HKEY_CURRENT_USER is associated with the default user, not the current user. To access another user's profile, impersonate the user, then access HKEY_CURRENT_USER.

关于C# Windows 服务需要修改注册表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1632280/

相关文章:

c# - EF Core GetNavigations 忽略集合

c# - 创建一个通用(但在声明时键入)表达式数组

.Net Windows 服务和 InstallState 文件 - 真的需要吗?

mysql - 在cmd控制台中显示utf-8的字体

xml - VS 2017 15.1 中的大型 XML 文件

c# - 未创建注册表项

c# - Serial port write究竟是如何从缓冲区写入数据的呢?

c# - 跨线程编码异常(响应式(Reactive)扩展)

http - WCF 有自己的网络服务器吗?

C# TCP 服务器停止接收客户端消息,在服务重新启动时恢复