且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

其他用户编辑注册表项

更新时间:2023-12-02 11:58:16

您可以模拟用户,然后修改注册表,目前的情况下。这里是C#和模拟一对夫妇的资源:

You can impersonate the user and then change the registry for that current context. Here are a couple of resources on C# and Impersonation:

  • Windows Impersonation using C#
  • Windows Impersonation from C#

您想要做的是这样的(伪):

What you want to do is something like this (pseudo):

using(var impersonation = new Impersonate(username,password))
{
    ChangeRegistry(keys, values);
}

而当模拟设置,你回来使用正在运行的用户。 下面是一个例子实施即实现IDisposable要像上图所示这里是伪exampel的模拟类另一个例子

And when the impersonation is disposed, you are back using the running user again. Here is an example implementation of an Impersonate class that implements IDisposable to act like the pseudo-exampel shown above and here is another example.

Here是你如何更改注册表值的示例:

var registry = Registry.CurrentUser;
var key =
registry.OpenSubKey(
   @"HKEY_CURRENT_USER\Some\Path\That\You\Want\ToChange", true);

key.SetValue(null, "");              
Registry.CurrentUser.Flush();

更新

所以,你需要为了做访问 HKCU 的是,你还必须加载用户配置文件。这是通过调用Win32的另一个方法被称为 LoadUserProfile 完成。有一个完整的例子这里,你可以用,但我会这里包括重要的位。

So what you need to do in order to access HKCU is that you also have to load the user profile. This is done by invoking another Win32 Method that is called LoadUserProfile. There's a complete example here that you can use, but I'm going to include the important bits here.

首先,你需要包括Win32的方法是这样的:

First you need to include the Win32 methods like this:

[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool LoadUserProfile(IntPtr hToken, 
                                         ref ProfileInfo lpProfileInfo);

[DllImport("userenv.dll",  CallingConvention = CallingConvention.Winapi, 
                           SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool UnloadUserProfile(IntPtr hToken, 
                                                   IntPtr lpProfileInfo);

在你的模拟使用块,你需要做到以下几点:

Inside your impersonation using-block you need to do the following:

ProfileInfo profileInfo = new ProfileInfo();
profileInfo.dwSize = Marshal.SizeOf(profileInfo);
profileInfo.lpUserName = userName;
profileInfo.dwFlags = 1;
Boolean loadSuccess = LoadUserProfile(tokenDuplicate, ref profileInfo);

和在这之后,你应该能够访问 HKCU 。当您完成后,您需要使用卸载配置文件 UnloadUserProfile(tokenDuplicate,profileInfo.hProfile);

And after this you should be able to access the HKCU. When you're done, you need to unload the profile using UnloadUserProfile(tokenDuplicate, profileInfo.hProfile);.