如何从 Windows 中提取/获取当前用户名?
这是我尝试过的:
Dim username As String = Application.ExecutablePath.ToString.Split("\")(0)
If username <> "" then
MsgBox(username)
End if
您可以通过此方法获取用户名:
声明函数:
Declare Function GetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, _
ByRef nSize As Integer) As Integer
方法:
功能:
Public Function GetUserName() As String
Dim iReturn As Integer
Dim userName As String
userName = New String(CChar(" "), 50)
iReturn = GetUserName(userName, 50)
GetUserName = userName.Substring(0, userName.IndexOf(Chr(0)))
End Function
利用:
Dim xstr As String = Space(255)
Dim max As Integer = 255
Dim rc As Integer
rc = GetUserName(xstr, max)
MessageBox.Show(Mid(xstr, 1, max))
GetUserName 函数检索与当前线程关联的用户的名称。
以及替代方法:
首先:
Dim username As String = Environment.UserName
第二:
Dim username2 As String = SystemInformation.UserName
不可取的方法:
MessageBox.Show(Application.ExecutablePath.ToString.Split("\")(2))
(你非常接近!,干得好。)
不要使用 msgbox()。
msgbox 适用于 Visual Basic 6。
MessageBox.Show 适用于 vb.net
如果您已System.Windows.Forms
导入,这也有效:
Dim username As String = SystemInformation.UserName
您也可以使用它来获取用户名:
Dim username As String =
Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process)("USERNAME")