Visual Basic Core Snippet Routines
   Retrieves the current default user name, or the user name used to establish a network connection.      
           Updated:   Monday December 26, 2011   
click to copy code:  

   Applies to:   VB4-32, VB5, VB6   
OS restrictions:   None  
 Code Snippet
' Copyright 1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
Private Const NERR_SUCCESS As Long = 0

Private Declare Function WNetGetUser Lib "Mpr" _
   Alias "WNetGetUserA" _
  (ByVal lpName As String, _
   ByVal lpUserName As String, _
   lpnLength As Long) As Long
Private Declare Function lstrlenW Lib "kernel32" _
  (ByVal lpString As Long) As Long
Private Function GetNetworkUserName() As String

  'Retrieves the current default user name,
  'or the user name used to establish a
  'network connection.
   Dim buff As String
   Dim nSize As Long
   buff = Space$(MAX_PATH)
   nSize = Len(buff)
  'get the user name of the current machine
  'logged on to network by passing vbNullString
  'as lpName
   If WNetGetUser(vbNullString, buff, nSize) = 0 Then
     'Call succeeded. This does not necessarily
     'mean however that the user has logged on
     'to the network, as WNetGetUser should
     'return the current user's Windows name
     'even if not logged on.
      GetNetworkUserName = TrimNull(buff)
    End If

End Function

Private Function TrimNull(startstr As String) As String

   TrimNull = Left$(startstr, lstrlenW(StrPtr(startstr)))
End Function

 Calling Syntax
   sUsername = GetCurrentUserName()

 Comments / Related
demo in use:    
Related:   GetUserName
NetUserGetInfo: Enumerate the User List and Obtain User Info  


PayPal Link
Make payments with PayPal - it's fast, free and secure!


Copyright 1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy


Hit Counter