Get the current username

Posted On 2007-05-22 by FortyPoundHead
Tags: VB6 Miscellaneous 
Views: 1752

Get the username of the currently logged on user.

Option Explicit

Private Const UNKNOWN = "(Value Unknown Because System Call Failed)"
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Public Function GetCurrentUserName() As String

  Dim l As Long
  Dim sUser As String

  sUser = Space$(255)
  l = GetUserName(sUser, 255)
  ' strip null terminator

  If l <> 0 Then
    GetCurrentUserName = Left(sUser, InStr(sUser, Chr(0)) - 1)
    Err.Raise Err.LastDllError, , "A system call returned an error code of " & Err.LastDllError
  End If

End Function

About the Author

FortyPoundHead has posted a total of 1974 articles.

Comments On This Post

No comments on this post yet!

Do you have a thought relating to this post? You can post your comment here. If you have an unrelated question, you can use the Q&A section to ask it.

Or you can drop a note to the administrators if you're not sure where you should post.

Your IP address is:

Before you can post, you need to prove you are human. If you log in, this test goes away.

Code Links