The Windows operating system provides for different user accounts so that each user can log on and have access to their files and settings. If you'd like to keep track of which users are running a Visual Basic 6 program, you'll need to determine the name of the current user and then store it in some manner. This article shows you how.
The API function GetUserName is designed specifically for this purpose. Its declaration is:
Declare Function GetUserName Lib "advapi32.dll"
Alias "GetUserNameA" _
(ByVal lpBuffer As String, nSize As Long) As Long
The first argument is a string that will be used to return the username; the second argument is a number giving the string's length. The return value is non-zero (True) on success and 0 (False) on failure. I've never seen this function fail, so I always omit checking the return value.
To use this function, you must create a string and fill it with spaces. The number of spaces will determine the length of the string and, therefore, the maximum length that can be returned as the username. Since people never choose long usernames, I find that a length of 40 is always more than adequate. Here's the code.
Dim UserName As String
UserName = Space(40)
Then, it's simply a matter of calling the GetUserName function, like this:
GetUserName UserName, Len(UserName)
After this call, the variable UserName will contain the name of the current user. Your program can use this as needed (e.g., saving it to a log file or the registry to keep track of who is using the program).
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!