Search code examples
c#windows-servicesregistry

C# Windows service needs to make registry changes


I have a service that needs to update the registry every 5 minutes (counteract GPO). The code runs fine in a regular application, but when I put it in a windows service, it doesn't make the changes. I am using the local system account for the service and it is not throwing any exceptions

The code below works in a regular console app but not in the service:

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

Any Ideas?

EDIT:

Thanks for the replies. I don't know why the "CurrentUser" escaped my attention. Thanks for pointing that out.

My problem still remains that the group policy is being pushed against the CurrentUser. Right now I am considering just creating an app that loads at startup and stays active. Any other suggestions would be welcome.

EDIT:

As to Will's comment, I am unable to find the UpdatePerUserSystemParameters function signature in the win32 API. Does that imply that it can be called without parameters?

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

Solution

  • See 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.