Writing From HKEY_USERS

1.2k Views Asked by At

I am attempting to create an application that will allow me to input a username and switch that user's default printer by modifying the registry under HKEY_USERS\UserSID. I cannot seem write values to that section of the registry though. Perhaps it's a Windows limitation? Here's the code I have so far.

    Dim strComputer = "."
    Dim objWMIService As Object = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Dim theUsername As String = TextBox1.Text
    Dim theDomain As String = TextBox2.Text

    Dim objAccount As Object = objWMIService.Get("Win32_UserAccount.Name='" & theUsername & "',Domain='" & theDomain & "'")

    Dim theport As RegistryKey
    theport = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion\\Devices")
    Dim val As Object = theport.GetValue(ListBox1.SelectedItem)
    theport.Close()
    Dim theSid As String = objAccount.sid
    Dim theKey As RegistryKey = Registry.Users.OpenSubKey(theSid + "\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows", True)
1

There are 1 best solutions below

0
On

I don't think that there is some Windows limitation, because I wrote to HKEY_USERS\SIDs many times. But I used for this purpose the vbscript. Also I should warn you that you can only read&write to Users registry if they are logged. For not logged users - use the ActiveSetup.

There is my script on vbs which writes some registry to all logged users. Hope you could adapt it to VB.NET.

Option Explicit

Const HKEY_USERS = &H80000003
Dim objReg, objWMI, colSessions, objSession, colList, colUsers, objUser, Domain, UserName, objUserAccount, SID, WshShell

Set WshShell = CreateObject("WScript.Shell")
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") 

Set colSessions = objWMI.ExecQuery("Select * from Win32_LogonSession Where LogonType = 2 Or LogonType = 10") 
If colSessions.Count <> 0 Then 
    For Each objSession in colSessions 
        Set colUsers = objWMI.ExecQuery("Associators of " & "{Win32_LogonSession.LogonId=" & objSession.LogonId & "} " & "Where AssocClass=Win32_LoggedOnUser Role=Dependent" )
        For Each objUser in colUsers 
            Domain = objUser.Domain : UserName = objUser.Name
            Set objUserAccount = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2:Win32_UserAccount.Domain='" & Domain & "',Name='" & UserName & "'")
            SID = objUserAccount.SID
            objReg.CreateKey HKEY_USERS, SID & "\Control Panel\Desktop"
            objReg.SetStringValue HKEY_USERS, SID & "\Control Panel\Desktop", "Example", "1"
            objReg.SetDwordValue HKEY_USERS, SID & "\Control Panel\Desktop", "Example", "2"         

        Next 
    Next 
End If