使用VB.NET查找当前登录用户的用户名 [英] Finding user name of current logged in user using VB.NET

查看:373
本文介绍了使用VB.NET查找当前登录用户的用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取当前用户的用户名.当我以Johnny Smith身份登录并在没有管理员特权的情况下运行我的应用程序时,它将为我返回正确的用户名Johnny Smith.但是问题是,当我右键单击并选择以管理员身份运行"时,Windows将以管理员登录屏幕提示我,并且登录后我的应用程序返回用户名admin,而不是当前登录的用户./p>

我尝试过:

strUserLabel.Text = Environment.UserName

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

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

strUserLabel.Text = strUser

在系统提示为管理员时,两个都给我管理员用户名.

解决方案

我已经弄清楚了.我使用了此功能,它将确定用户正在使用哪个进程.在我的代码中,我定义了寻找explorer.exe进程的用户名的地方.

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

索引( 0 )将返回用户名

1 中的

索引将返回用户的域名

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.

解决方案

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

这篇关于使用VB.NET查找当前登录用户的用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆