Friday 5 August 2016

visual studio 2010 - 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 admin, not the user which is logged in currently.



I have tried:



strUserLabel.Text = Environment.UserName


Also



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.


Answer



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
Next
End Function


Index of 0 will return username



Index of 1 will return domain name of user


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...