Connecting Tech Pros Worldwide Forums | Help | Site Map

Function to return Username (NT Login) of current user

msquared's Avatar
Administrator
 
Join Date: Aug 2006
Location: Dublin, Ireland
Posts: 10,884
#1   May 29 '07
This function returns the username of the currently logged in NT User.

Expand|Select|Wrap|Line Numbers
  1. ' This library must be declared
  2. Declare Function GetUserName& _
  3.                      Lib "advapi32.dll" Alias _
  4.                      "GetUserNameA" (ByVal lpBuffer As String,
  5.                                      nSize As Long)
  6.  
  7. Function sys_OrigUserID() As String
  8. Dim s$, cnt&, dl&
  9. Dim max_String As Integer
  10. Dim username As String
  11.  
  12.     max_String = 30
  13.     cnt& = 199
  14.     s$ = String$(max_String, 1)
  15.     dl& = GetUserName(s$, cnt)
  16.     username = Trim$(Left$(s$, cnt))
  17.     username = UCase(Mid(username, 1, Len(username) - 1))
  18.     sys_OrigUserID = username
  19.  
  20. End Function



nico5038's Avatar
Moderator
 
Join Date: Nov 2006
Location: The Netherlands
Posts: 2,232
#2   May 29 '07

re: Function to return Username (NT Login) of current user


As an alternative you can use the Environ() function like:
Expand|Select|Wrap|Line Numbers
  1. strUser = Environ("username")
  2.  
This Environ() function can be used to extract all system variables like the computername, etc. as long as the variable has been defined and has been filled.

To get all available variables you can open the cmd window (Start / Run.. and enter the string "cmd") now by typing SET after the "C:>" prompt and pressing [Enter] all available variables (including the "username") will show and all of these can be extracted with this Environ() function. Keep however in mind that not all variables will be available on all computers...

Nic;o)
NeoPa's Avatar
Administrator
 
Join Date: Oct 2006
Location: London - UK
Posts: 15,727
#3   Nov 20 '07

re: Function to return Username (NT Login) of current user


Bear in mind also that the Environ() function will return whatever is in the Environment Variable "USERNAME". While this is set up with the username, there's nothing to stop it being changed within a session. If you're using this as part of a security feature then it's best to use GetUserName().
Reply