There are a few ways to get the Windows current logged on user name.
1. The Environment Variable:
Using the environment variables are easy to use but unreliable for these reasons -
- The user can edit the value to anything they want by going to the System Properties and changing the values.
- The user can delete the environment variables too.
To get the username this way is simple:
VB Code:
Option Explicit Private Sub Command1_Click() MsgBox Environ("USERNAME") End Sub
2. Using the API:
There are two APIs that can retrieve the user name.
• The GetEnvironmentVariable API:
It is just another way to read an environment variable (and as such, has the same problems mentioned above).
VB Code:
Option Explicit Private Declare Function GetEnvironmentVariable Lib "kernel32" Alias "GetEnvironmentVariableA" _ (ByVal lpName As String, ByVal lpBuffer As String, ByVal nSize As Long) As Long Private Sub Command1_Click() Dim strUserName As String * 255 'Create a string buffer of 255 chars in length Dim x As Integer x = GetEnvironmentVariable("USERNAME", strUserName, Len(strUserName)) If x > 0 Then 'Look for Null Character, usually included x = InStr(strUserName, vbNullChar) 'Trim off buffered spaces too If x > 0 Then MsgBox (Left$(strUserName, x - 1)) Else MsgBox (Left$(strUserName, x)) End If End If End Sub
• The GetUserName API:
It is probably the most reliable and secure way to retrieve the username. It cannot be changed by the user as long as Windows permissions dissallow it.
VB Code:
'If placed in a module it will be available to all forms in your project for calling 'Inside Module1.bas Option Explicit Private Declare Function GetUserName Lib "advapi32.dll" _ Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long Public Function CurrentUser() As String '********************************************************* '* Function to get the current logged on user in windows * '********************************************************* Dim strBuff As String * 255 Dim X As Long CurrentUser = "" X = GetUserName(strBuff, Len(strBuff) - 1) If X > 0 Then 'Look for Null Character, usually included X = InStr(strBuff, vbNullChar) 'Trim off buffered spaces too If X > 0 Then CurrentUser = UCase(Left$(strBuff, X - 1)) 'UCase is optional ;) Else CurrentUser = UCase(Left$(strBuff, X)) End If End If End Function 'Sample usage: 'Behind Form1.frm (or whatever your form's name is) Option Explicit Private Sub Form_Load() MsgBox CurrentUser End Sub
Note: all of these examples use message boxes to display the user name, but you can put the user name into a variable instead by replacing MsgBox in each of the examples with Variable = (where Variable is the name of a String variable). In the last example, you could use this as the form code to put the user name into the variable sUserName:
VB Code:
Option Explicit Dim sUserName as String Private Sub Form_Load() sUserName = CurrentUser End Sub
Enjoy
Gangsta Yoda™®



Reply With Quote