Get Current logged on Username – – using advapi32.dll

Note this codes about 6 years old as of 2014 – I’m sure there are better ways of doing this now but this worked at the time and is still live in one of my projects.

I needed to identify the currently logged on user running my application to make an audit file and also show only user options that the logged on user was setup for.

Here’s the code…

Declare Function GetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, _
ByRef nSize As Integer) As Integer

   Public Function GetUserName() As String
        'Gets currently logged on user - username
        Dim iReturn As Integer
        Dim userName As String
        'put the username in a string limit 50 chars
        userName = New String(CChar(" "), 50)
        'put the length of the username in an Integer iReturn
        iReturn = GetUserName(userName, 50)
        'Tidy up various formatting if required with the replace function like remove the .
        userName = userName.Replace("."c, " "c)
        'Return the username back
        GetUserName = userName.Substring(0, userName.IndexOf(Chr(0)))

    End Function

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.