VB CAD Tips

www.vbcad.com

Get the user name used to log in to Windows
 
The Windows API gives us a function called 'GetUserName'.  This function does exactly that.  Since the function is extracted from a .dll, we must declare the function in the General Declarations area of a Code Module (not a Class Module).

So, the first thing we need to do is procide the functionction declaration.

'General Declarations area of a Code Module
Public Declare Function GetUserName& Lib "advapi32.dll" Alias "GetUserNameA" _
                            (ByVal lpBuffer As String, nSize As Long)

After declaring the function, we put it to use in a test procedure.  You will notice that we must load the variable that will contain the log-in name with spaces.  We also load the variable containing the number of characters in the log-in name with a max size of 255 characters.

After using GetUserName, we get all except the last character from the UName variable.

Sub TstGetUserName() 'This will test the use of GetUserName.
   Dim UName As String
   Dim UNameLen As Long
   Dim X as Long
   UName = Space(255)
   UNameLen = 255
   X = GetUserName(UName, UNameLen)
   If X <> 0 Then
'We got the user's name
         UName = Left(UName, UNameLen - 1) 'Get all except the last character
         MsgBox "The current user is: " & vbCr & UName
      Else
         MsgBox "Unable to get the user name."
   End If
End Sub

Once we know the user name, we can provide the functionality appropriate for that user or go to the user's specified work directory to log activities, etc.

Happy Programming!

Back to Tips ©2000 by VB CAD  All rights reserved.         www.vbcad.com