VB / Windows NT Security


Thread Starter

Niall M Watson

Dear List

Is it possible to access the logon name of the current workstation user in VB Runtime???
Thanks in advance for any tips!

PES Automation Ltd.

Niall Watson

Phone: 01283 741333 Fax: 01283 562303

Glass, Philip

You can do it with the following API call:

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

Here's an example of how to use the function:

Dim s$, cnt&, dl&
cnt& = 199
s$ = String$(200, 0)
dl& = GetUserName(s$, cnt)
Debug.Print Left$(s$, cnt)

This will get you the user name.
You can use that wherever you wish.

Hope this helps.

Philip L. Glass
Computer Geek
Brown and Caldwell
[email protected]

Ranjan Acharya

It is in the environment under USERNAME. Just look up functions to read environment variables. If there is not one in VB's DLLs then you could make a call to the Win32 API where there should be something of the sort (I hope).


Pierre R. Hinse CET

Try this inside your vb code:

Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal lpbuffer As String, nSize As Long) As Long

Dim sBuffer As String
Dim lSize As Long

sBuffer = Space$(255)
lSize = Len(sBuffer)
Call GetUserName(sBuffer, lSize)
If lSize > 0 Then
txtUserName.Text = Left$(sBuffer, lSize)
txtUserName.Text = vbNullString
End If

Have Fun!
Pierre R. Hinse CET

Wallinius Mattias

Yes, but only through great pain. Use C++ to access the SSPI and wrap it in a COM server. Doesn't need to be large one.

MORON, Olivier


You can do it like following:

You'll have to to create a module and to declare a function like following and to use it. The example below is retrieving the user name and the computer name, then concatenating them into one string and returning the string.

Declare Function GetComputerName Lib "Kernel32" Alias "GetComputerNameA"
(ByVal lpBuffer As String, nSize As Long) As Long
Declare Function GetUserName Lib "Advapi32" Alias "GetUserNameA" (ByVal
lpBuffer As String, nSize As Long) As Long

Public Function GetUserComputerName() As String

Dim cpname As String * 1024
Dim cpsize As Long
Dim usname As String * 1024
Dim ussize As Long
Dim ret As Long

ussize = 1023
cpsize = 1023

On Error GoTo Error1
ret = GetComputerName(cpname, cpsize)
If (ret = 0) Or (cpsize = 0) Then GoTo Error1

On Error GoTo Error2
ret = GetUserName(usname, ussize)
If (ret = 0) Or (ussize = 0) Then GoTo Error2

GetUserComputerName = Left(usname, ussize - 1) + " " + Left(cpname,
cpsize - 1)
Exit Function

GetUserComputerName = "Unknown computer"
Exit Function
GetUserComputerName = "Unknown user"
Exit Function

End Function

Best regards,

Olivier Moron

R&D Project Manager
My personal web site, Software And Automation Technical Search Engine :

Can I establish my own logon process through programing interface instead of the interactive WinLogon process?