I.7. Determine the User Name

Often, you'll need to know the current user of the application. This might be to determine what activities they are allowed to do or to stamp records with change logging information. There are two user names that you'll be concerned with: the current Access user and the current Windows user.

I.7.1. The Current Access User

The current Access user is determined using the built-in CurrentUser function. However, if you are not using Access security and requiring the user to log in with a User Name and Password, this user name will always be the default Access user of "Admin". This isn't too descriptive, so you may need to know the name of the user that is currently using this PC.

I.7.2. The Current Windows User

To determine the currently logged in Windows user, you can use this code. First, in the module declaration section, include this code:

Global Const ERRORMOREDATA = 234
Global Const ERR_SUCCESS = 0

Private Declare Function WNetGetUser Lib "mpr" Alias _
"WNetGetUserA" (ByVal lpName As String, _
ByVal lpUserName As String, lpnLength As Long) As Long

Then, create a function with this code:

Public Function WinUserName() As String
    Dim lUserNameLen As Long
    Dim stTmp As String
    Dim lReturn As Long

    Do
        ' Set up the buffer
        stTmp = String$(lUserNameLen, vbNullChar)

        lReturn = WNetGetUser(vbNullString, stTmp, lUserNameLen)

        ' Continue looping until the call succeeds or the buffer
        ' can't fit any more data
    Loop Until lReturn <> ERRORMOREDATA

    If lReturn = ERR_SUCCESS Then
        WinUserName = Left$(stTmp, InStr(1, stTmp, vbNullChar, _
        vbBinaryCompare) - 1)
    End If

End Function

You can use this Windows user name anywhere you like, including displaying it on forms, using it to allow or disallow certain features, or including the user name whenever a record is changed or created.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.170.174