Using VB6, how do I get the current user and domai

2020-02-12 08:15发布

问题:

I need the current user and the domain. I am using a VB 6 application.

Thanks

回答1:

One way would be to ask the environment:

Dim UserName As String
Dim UserDomain As String
UserName   = Environ("USERNAME")
UserDomain = Environ("USERDOMAIN")

(Works on Windows NT and up only, obviously.)



回答2:

And the API-version:

Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long  

Declare Function LookupAccountName Lib "advapi32.dll" Alias "LookupAccountNameA" (lpSystemName As String, ByVal lpAccountName As String, sid As Any, cbSid As Long, ByVal ReferencedDomainName As String, cbReferencedDomainName As Long, peUse As Long) As Long

Private Sub Form_Load()  
     Dim sDomainName As String * 255   
     Dim lDomainNameLength As Long     
     Dim sUserName as String
     Dim bUserSid(255) As Byte      
     Dim lSIDType As Long 

    Rem Create a buffer
    sUserName = String(100, Chr$(0))  

    Rem Get the username
     GetUserName sUserName, 100  

    Rem strip the rest of the buffer
    sUserName = Left$(sUserName, InStr(sUserName, Chr$(0)) - 1)

     rem Show the temppath and the username
     MsgBox "Hello " + strUserName 

     lResult = LookupAccountName(vbNullString, sUserName, bUserSid(0), 255, sDomainName, lDomainNameLength, _
  lSIDType)
    if lResult <>0 then
       msgbox sDomainName
    end if
end sub


回答3:

Use the following methods of the WshNetwork object, which is available after you reference the Windows Script Host Object Model in your project:

Dim Network As WshNetwork
Set Network = New WshNetwork

Debug.Print "ComputerName: " & Network.ComputerName
Debug.Print "UserDomain: " & Network.UserDomain
Debug.Print "UserName: " & Network.UserName

I cast the results to upper or lower case for consistency, but those are the methods you need.

Note that when run on a machine that's not logged into a domain, both ComputerName and UserDomain return the same thing -- the computer name.



回答4:

Basically you need to make Windows API calls. Searching vbnet.mvps.org I get the following answers.

  • get domain name
  • get thread user name (run as)
  • get logged on user


回答5:

What about this?

Private Function IsAdmin() As Boolean
Dim groups As Object
Dim user As Object

Set groups = GetObject("WinNT://./administrators")

For Each user In groups.members

If UCase(Environ("USERNAME")) = UCase(user.Name) Then
IsAdmin = True
End If

Next user

End Function