您的位置:首页 > 编程语言 > C#

Windows服务中操作HKEY_CURRENT_USER注册表

2017-01-03 17:16 555 查看
主要思想是:在Windows服务(System)中,通过模拟用户登录,获得Session ID,然后对当前用户注册表项操作。

public IntPtr GetTokenAsCurrentUser()

{

IntPtr hTokenUser = IntPtr.Zero;

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

if (String.Compare(@”NT AUTHORITY\SYSTEM”, userName, true) == 0)

{

int consoleSessionId = WTSGetActiveConsoleSessionId();

if (WTSQueryUserToken(consoleSessionId, out hTokenUser))

{

return hTokenUser;

}

}

return hTokenUser;

}

public bool GetCurrentUserSID(ref string CurrentUserSID)

{

IntPtr hUserToken = GetTokenAsCurrentUser();

if (hUserToken != IntPtr.Zero)

{

if (!ImpersonateLoggedOnUser(hUserToken))

{

return false;

}

CloseHandle(hUserToken);

System.Security.Principal.WindowsIdentity windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
CurrentUserSID = windowsIdentity.User.ToString();

if (!RevertToSelf())//come back
{
}
return true;
}
return false;


}

public void Do()

{

string CurrentUserSID = string.Empty;

if (CTControlCenter.Common.AnalogLogon.AnalogLogon.GetCurrentUserSID(ref CurrentUserSID))

{

RegistryKey rsg = Registry.Users.OpenSubKey(CurrentUserSID + “\” + @”Software\Microsoft”, true);

if (rsg != null)

{

rsg.Close();

}

}

}

注:部分API属于C++接口,需要导入使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# 模拟登录