Skip Navigation Links.
Win32API Example - GetUserName
Language(s):Visual Basic 6.0
Category(s):API

How to get the UserName of the current user.

'Win32API Example - GetUserName
'
'Jon Vote
'
'02/2002

' 1) Create a new project. Form1 will be created by default.
' 2) Add a label to the form. 
' 3) Add a command button below the label.
' 4) Paste the following code into the declarations section of Form1:

' --- Begin code for Form1 ---

'Windows API Example: GetUserName
'
'Author: Jon Vote 
'        Idioma Software Inc. 
'        www.idioma-software.com 
'
'Date:   02/02
'
'(c) 2002 Idioma Software Inc. 


Option Explicit

Private Sub Form_Load()
  
  Me.Caption = "GetUserName example"
  Label1.Caption = ""
  Command1.Caption = "GetUser&Name"
  Command1.Default = True 

End Sub

Private Sub Command1_Click()
  
  Label1.Caption = vbGetUserName
  
End Sub

' --- End code for Form1 ---

' 6) From the menu select Project|Add Module. Module1 will be created by default
' 7) Paste the followin code into Module1:

' --- Begin code for Module1 ---

Option Explicit

Public Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

'Wraps the GetUserName API
Public Function vbGetUserName() As String

  Dim lngRC As Long
  Dim strUserName As String
  Dim intZeroPos As Integer
  Const MAX_STRING_LENGTH = 256
  
  strUserName = Space$(MAX_STRING_LENGTH)
  lngRC = GetUserName(strUserName, MAX_STRING_LENGTH)
  intZeroPos = InStr(strUserName, Chr$(0))
  If intZeroPos = 0 Then
    vbGetUserName = strUserName
  Else
    vbGetUserName = Left$(strUserName, intZeroPos - 1)
  End If
  
End Function

' --- End code for Module1 ---


This article has been viewed 5438 times.
The examples on this page are presented "as is". They may be used in code as long as credit is given to the original author. Contents of this page may not be reproduced or published in any other manner what so ever without written permission from Idioma Software Inc.