Mario LIPCIK Mario LIPCIK - 5 months ago 20 Question

Finding user name of current logged in user using VB.NET

I'm trying to get the user name of the current user. When I log in as

Johnny Smith
and run my application without administrator privileges it will return me the correct user name,
Johnny Smith
. But the problem is that when I right click and choose "Run as Administrator", Windows will prompt me with a login screen for the administrator and after login my application returns user name
, not the user which is logged in currently.

I have tried:

strUserLabel.Text = Environment.UserName


Dim WSHNetwork = CreateObject("WScript.Network")
Dim strUser = ""

While strUser = ""
strUser = WSHNetwork.Username
End While

strUserLabel.Text = strUser

Both return me the administrator user name when prompted as administrator.


I have figured it out. I used this function which will determine which process which the user is using. In my code I defined that look for username of the explorer.exe process.

Function GetUserName() As String

    Dim selectQuery As Management.SelectQuery = New Management.SelectQuery("Win32_Process")
    Dim searcher As Management.ManagementObjectSearcher = New Management.ManagementObjectSearcher(selectQuery)
    Dim y As System.Management.ManagementObjectCollection
    y = searcher.Get

    For Each proc As Management.ManagementObject In y
        Dim s(1) As String
        proc.InvokeMethod("GetOwner", CType(s, Object()))
        Dim n As String = proc("Name").ToString()
        If n = "explorer.exe" Then
            Return s(0)
        End If
End Function

Index of 0 will return username

Index of 1 will return domain name of user