Next, enter a function to return the user name. Enter the following code in the same
module:
Public Function ReturnUserName()
Dim strUser As String, X As Integer
strUser = Space$( 256 )
X = GetUserName(strUser, 256 )
strUser = RTrim(strUser)
ReturnUserName = Left(strUser, Len(strUser) - 1 )
End Function
The code sets up variables to hold a string buffer to accept the user name and to hold the
return value from the API call (true or false according to success or failure).
TheSpaces$function is then used to create a string buffer of 256 characters, which is the
maximum size for a Windows user name. The APIGetUserNameis then called, which loads
the user name into the bufferstrUser.
The RTrim function is used to remove all the trailing spaces in the buffer. Because the
buffer is made up of 256 spaces, and in my experience Windows user names are generally
under ten characters, there will be many spaces left over that will need removing.
Finally, the last character of the remaining string is removed. This is because the API call
returns the string with a carriage return delimiter. The next logical step is to check that this
user should be entering your application and to do that you do not need the carriage return.
To make use of this function, create a new form (see Chapter 9 on how to do this) or use
an existing one and add the following code to the form open event:
MsgBox ReturnUserName()
You can find the form open event by right-clicking the form and selecting Build Event
from the pop-up menu. Select Code Builder, which will open the VBE window for the form.
Select Form from the top-left drop-down and choose Open from the top-right drop-down of
the window.
Open the form in View mode by clicking the View icon in the View group of the ribbon.
Your user name will then appear as a message box. If you ask a colleague to run the application
on their PC, the message box will display their user name.
By placing the call to your function in the startup form for your application (refer to
Chapter 9 for more information), you have a very reliable means of instantly discovering
who is entering your application.
This can, of course, be easily circumvented by the user holding theSHIFTorBYPASSkey
down when the application is loading. Ways to lock the database and prevent a user from
doing this are discussed more thoroughly in Chapter 24.
280 Microsoft Access 2010 VBA Macro Programming