Your VB code doesn't resemble the code you link to.
Try this:
Public Shared Function GetUsernameBySessionId(ByVal sessionId As Integer) As String
Dim buffer As IntPtr
Dim strLen As Integer
Dim username = "SYSTEM"
If WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLASS.WTSUserName, buffer, strLen) AndAlso strLen > 1 Then
username = Marshal.PtrToStringAnsi(buffer)
WTSFreeMemory(buffer)
If WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLASS.WTSDomainName, buffer, strLen) AndAlso strLen > 1 Then
username = Marshal.PtrToStringAnsi(buffer) & "\" & username
WTSFreeMemory(buffer)
End If
End If
Return username
End Function
Note the nested
If
which does a second fetch from the Domain, and the preset value for
username