How to get the client name of a terminal services session
This is how to return the client computer name of a Windows Terminal Services session (running on Windows 2000) -
Code:
Public Declare Function WTSQuerySessionInformation Lib "wtsapi32.dll" Alias "WTSQuerySessionInformationA" (ByVal hServer As Long, ByVal SessionID As Long, ByVal InfoClass As Long, ByRef ppBuffer As Long, ByRef pBytesReturned As Long) As Long
Public Declare Sub WTSFreeMemory Lib "wtsapi32.dll" (ByVal pMemory As Long)
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Long, ByVal Length As Long)
Public Const WTS_CURRENT_SERVER_HANDLE As Long = 0
Public Const WTS_CURRENT_SESSION As Long = -1
Public Const WTSClientName As Long = 10
Public Function GetWTSClientName() As String
'This returns the name of the Windows Terminal Services client name that
'this server session is connected to.
Dim strBuffer As String
Dim lpBuffer As Long
Dim RetVal As Long
Dim pBytes As Long
RetVal = WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSClientName, lpBuffer, pBytes)
If RetVal Then
GetWTSClientName = GetStringFromLP(lpBuffer)
WTSFreeMemory lpBuffer
End If
End Function
Private Function GetStringFromLP(ByVal StrPtr As Long) As String
'Returns a string, given the pointer to it
Dim b As Byte
Dim TempStr As String
Dim BufferStr As String
Dim Done As Boolean
Done = False
Do
CopyMemory ByVal VarPtr(b), ByVal StrPtr, 1
If b = 0 Then
Done = True
Else
TempStr = Chr$(b)
BufferStr = BufferStr & TempStr
StrPtr = StrPtr + 1
End If
Loop Until Done
GetStringFromLP = BufferStr
End Function