WTSEnumerateSessions (wtsapi32)
Last changed: -62.209.223.226

.
Summary
TODO - a short description

C# Signature:

   [DllImport("wtsapi32.dll", SetLastError=true)]
   static extern void WTSEnumerateSessions(
     System.IntPtr hServer,
     int Reserved,
     int Version,
     ref System.IntPtr ppSessionInfo,
     ref int pCount);

   static extern void WTSEnumerateSessions(
      System.IntPtr hServer,
      ref System.IntPtr ppSessionInfo,
      ref int pCount)
   {
      WTSEnumerateSessions(hServer,0,1,ppSessionInfo,pCount);
   }

VB Signature:

    <DllImport("wtsapi32.dll", _
    bestfitmapping:=True, _
    CallingConvention:=CallingConvention.StdCall, _
    CharSet:=CharSet.Auto, _
    EntryPoint:="WTSEnumerateSessions", _
    setlasterror:=True, _
    ThrowOnUnmappableChar:=True)> _
    Private Shared Function WTSEnumerateSessions( _
    ByVal hServer As IntPtr, _
    <MarshalAs(UnmanagedType.U4)> _
    ByVal Reserved As Int32, _
    <MarshalAs(UnmanagedType.U4)> _
    ByVal Version As Int32, _
    ByRef ppSessionInfo As IntPtr, _
    <MarshalAs(UnmanagedType.U4)> _
    ByRef pCount As Int32) As Int32
    End Function

User-Defined Types:

    Private Enum WTS_CONNECTSTATE_CLASS
    WTSActive
    WTSConnected
    WTSConnectQuery
    WTSShadow
    WTSDisconnected
    WTSIdle
    WTSListen
    WTSReset
    WTSDown
    WTSInit
    End Enum

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
    Private Structure WTS_SESSION_INFO
    Dim SessionID As Int32 'DWORD integer
    Dim pWinStationName As String ' integer LPTSTR - Pointer to a null-terminated string containing the name of the WinStation for this session
    Dim State As WTS_CONNECTSTATE_CLASS
    End Structure

Notes:

None.

Tips & Tricks:

Please add some!

Sample Code:

Option Explicit On
Option Strict On

Imports System.Runtime.InteropServices

Public Class ManagedWTSAPI

    Private Enum WTS_CONNECTSTATE_CLASS
    WTSActive
    WTSConnected
    WTSConnectQuery
    WTSShadow
    WTSDisconnected
    WTSIdle
    WTSListen
    WTSReset
    WTSDown
    WTSInit
    End Enum

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
    Private Structure WTS_SESSION_INFO
    Dim SessionID As Int32 'DWORD integer
    Dim pWinStationName As String ' integer LPTSTR - Pointer to a null-terminated string containing the name of the WinStation for this session
    Dim State As WTS_CONNECTSTATE_CLASS
    End Structure

    Friend Structure strSessionsInfo
    Dim SessionID As Integer
    Dim StationName As String
    Dim ConnectionState As String
    End Structure

    <DllImport("wtsapi32.dll", _
    bestfitmapping:=True, _
    CallingConvention:=CallingConvention.StdCall, _
    CharSet:=CharSet.Auto, _
    EntryPoint:="WTSEnumerateSessions", _
    setlasterror:=True, _
    ThrowOnUnmappableChar:=True)> _
    Private Shared Function WTSEnumerateSessions( _
    ByVal hServer As IntPtr, _
    <MarshalAs(UnmanagedType.U4)> _
    ByVal Reserved As Int32, _
    <MarshalAs(UnmanagedType.U4)> _
    ByVal Vesrion As Int32, _
    ByRef ppSessionInfo As IntPtr, _
    <MarshalAs(UnmanagedType.U4)> _
    ByRef pCount As Int32) As Int32
    End Function

    <DllImport("wtsapi32.dll")> _
    Private Shared Sub WTSFreeMemory(ByVal pMemory As IntPtr)
    End Sub

    <DllImport("wtsapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
     Private Shared Function WTSOpenServer(ByVal pServerName As String) As IntPtr
    End Function

    <DllImport("wtsapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
     Private Shared Sub WTSCloseServer(ByVal hServer As IntPtr)
    End Sub

    Friend Function GetSessions(ByVal ServerName As String) As strSessionsInfo()
    Dim ptrOpenedServer As IntPtr
    Dim RetVal As strSessionsInfo()
    Try
        ptrOpenedServer = WTSOpenServer(ServerName)
        Dim FRetVal As Int32
        Dim ppSessionInfo As IntPtr = IntPtr.Zero
        Dim Count As Int32 = 0
        Try
        FRetVal = WTSEnumerateSessions(ptrOpenedServer, 0, 1, ppSessionInfo, Count)
        If FRetVal <> 0 Then
            Dim sessionInfo() As WTS_SESSION_INFO = New WTS_SESSION_INFO(Count) {}
            Dim i As Integer
            For i = 0 To Count - 1 ' Step i + 1
            sessionInfo(i) = CType(Marshal.PtrToStructure(ppSessionInfo, GetType(WTS_SESSION_INFO)), WTS_SESSION_INFO)
            Next
            WTSFreeMemory(ppSessionInfo)
            Dim tmpArr(sessionInfo.GetUpperBound(0)) As strSessionsInfo
            For i = 0 To tmpArr.GetUpperBound(0)
            tmpArr(i).SessionID = sessionInfo(i).SessionID
            tmpArr(i).StationName = sessionInfo(i).pWinStationName
            tmpArr(i).ConnectionState = GetConnectionState(sessionInfo(i).State)
            Next
            ReDim sessionInfo(-1)
            RetVal = tmpArr
        Else
            Throw New ApplicationException("No data retruned")
        End If
        Catch ex As Exception
        Throw New Exception(ex.Message & vbCrLf & System.Runtime.InteropServices.Marshal.GetLastWin32Error)
        End Try
    Catch ex As Exception
        Throw New Exception(ex.Message)
        Exit Function
    Finally
        WTSCloseServer(ptrOpenedServer)
    End Try

    Return RetVal
    End Function

    Private Function GetConnectionState(ByVal State As WTS_CONNECTSTATE_CLASS) As String
    Dim RetVal As String
    Select Case State
        Case WTS_CONNECTSTATE_CLASS.WTSActive
        RetVal = "Active"
        Case WTS_CONNECTSTATE_CLASS.WTSConnected
        RetVal = "Connected"
        Case WTS_CONNECTSTATE_CLASS.WTSConnectQuery
        RetVal = "Query"
        Case WTS_CONNECTSTATE_CLASS.WTSDisconnected
        RetVal = "Disconnected"
        Case WTS_CONNECTSTATE_CLASS.WTSDown
        RetVal = "Down"
        Case WTS_CONNECTSTATE_CLASS.WTSIdle
        RetVal = "Idle"
        Case WTS_CONNECTSTATE_CLASS.WTSInit
        RetVal = "Initializing."
        Case WTS_CONNECTSTATE_CLASS.WTSListen
        RetVal = "Listen"
        Case WTS_CONNECTSTATE_CLASS.WTSReset
        RetVal = "reset"
        Case WTS_CONNECTSTATE_CLASS.WTSShadow
        RetVal = "Shadowing"
        Case Else
        RetVal = "Unknown connect state"
    End Select
    Return RetVal
    End Function

End Class

Sample Code:

    /// <summary>
    ///
    /// Nice Wrapper Class To TS API
    ///
    /// Darrell John Marjoram
    /// darrell@no_spam_md2solutions.co.uk
    ///
    /// 22 Feb 2005
    ///
    /// </summary>
    public class ManagedWTSAPI
    {

        [DllImport("wtsapi32.dll", CharSet=CharSet.Auto)]
        private static extern bool WTSEnumerateSessions(
            IntPtr hServer,
            [MarshalAs(UnmanagedType.U4)]
            int Reserved,
            [MarshalAs(UnmanagedType.U4)]
            int Version,
            ref IntPtr ppSessionInfo,
            [MarshalAs(UnmanagedType.U4)]
            ref int pCount);

        [DllImport("wtsapi32.dll")]
        static extern int WTSFreeMemory(IntPtr pMemory);

        [DllImport("wtsapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        static extern IntPtr WTSOpenServer(string pServerName);

        [DllImport("wtsapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        static extern void WTSCloseServer(IntPtr hServer);

        public enum WTS_CONNECTSTATE_CLASS
        {
            WTSActive,
            WTSConnected,
            WTSConnectQuery,
            WTSShadow,
            WTSDisconnected,
            WTSIdle,
            WTSListen,
            WTSReset,
            WTSDown,
            WTSInit
        }

        [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
        private struct WTS_SESSION_INFO
        {
            public int SessionId;
            public string pWinStationName;
            public WTS_CONNECTSTATE_CLASS State;
        }

        public struct SessionsInfo
        {
            public int SessionId;
            public string StationName;
            public string ConnectionState;
        }

        private static string GetConnectionState(WTS_CONNECTSTATE_CLASS State)
        {
            string RetVal;

            switch(State)
            {
                case WTS_CONNECTSTATE_CLASS.WTSActive:
                    RetVal = "Active";
                    break;
                case WTS_CONNECTSTATE_CLASS.WTSConnected:
                    RetVal = "Connected";
                    break;
                case WTS_CONNECTSTATE_CLASS.WTSConnectQuery:
                    RetVal = "Query";
                    break;
                case WTS_CONNECTSTATE_CLASS.WTSDisconnected:
                    RetVal = "Disconnected";
                    break;
                case WTS_CONNECTSTATE_CLASS.WTSDown:
                    RetVal = "Down";
                    break;
                case WTS_CONNECTSTATE_CLASS.WTSIdle:
                    RetVal = "Idle";
                    break;
                case WTS_CONNECTSTATE_CLASS.WTSInit:
                    RetVal = "Initialising";
                    break;
                case WTS_CONNECTSTATE_CLASS.WTSListen:
                    RetVal = "Listen";
                    break;
                case WTS_CONNECTSTATE_CLASS.WTSReset:
                    RetVal = "Reset";
                    break;
                case WTS_CONNECTSTATE_CLASS.WTSShadow:
                    RetVal = "Shadowing";
                    break;
                default:
                    RetVal = "Unknown connect state";
                    break;

            }

            return RetVal;
        }

        public static SessionsInfo[] GetSessions(string serverName)
        {
            IntPtr ptrOpenedServer = IntPtr.Zero;
            SessionsInfo[] RetVal;

            try
            {
                IntPtr buffer = IntPtr.Zero;
                Int32 Count = 0;

                ptrOpenedServer = WTSOpenServer(serverName);

                try
                {
                    if(WTSEnumerateSessions(ptrOpenedServer, 0, 1, ref buffer, ref Count))
                    {

                        // Marshal to a structure array here.  Create the array first.
                        WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[Count];

                        int Size = Marshal.SizeOf(new WTS_SESSION_INFO());

                        // Cycle through and copy the array over.
                        for(int index = 0; index < Count; index++)
                        {
                            // Marshal the value over.
                            IntPtr CurIdxPtr = new IntPtr(buffer.ToInt64() + (Size * index));

                            sessionInfo[index] = (WTS_SESSION_INFO)Marshal.PtrToStructure(
                                CurIdxPtr, typeof(WTS_SESSION_INFO));
                        }

                        WTSFreeMemory(buffer);

                        SessionsInfo[] tmpArr = new SessionsInfo[sessionInfo.Length];

                        for(int i=0; i<tmpArr.Length; i++)
                        {
                            tmpArr[i].SessionId = sessionInfo[i].SessionId;
                            tmpArr[i].StationName = sessionInfo[i].pWinStationName;
                            tmpArr[i].ConnectionState = GetConnectionState(sessionInfo[i].State);
                        }

                        RetVal = tmpArr;
                    }
                    else
                    {
                        throw new ApplicationException("No data returned");
                    }
                }
                catch(Exception ex)
                {
                    throw new Exception(ex.Message + "\r\n" + Marshal.GetLastWin32Error());
                }

            }
            finally
            {
                if(ptrOpenedServer != IntPtr.Zero) WTSCloseServer(ptrOpenedServer);
            }

            return RetVal;
        }

    }

Alternative Managed API:

Do you know one? Please contribute it!

Documentation