wtsquerysessioninformation (wtsapi32)
Last changed: -109.231.227.156

.
Summary

C# Signature:

  /// <summary>
/// The WTSQuerySessionInformation function retrieves session information for the specified
/// session on the specified terminal server.
/// It can be used to query session information on local and remote terminal servers.
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/termserv/termserv/wtsquerysessioninformation.asp
/// </summary>
/// <param name="hServer">Handle to a terminal server. Specify a handle opened by the WTSOpenServer function,
/// or specify <see cref="WTS_CURRENT_SERVER_HANDLE"/> to indicate the terminal server on which your application is running.</param>
/// <param name="sessionId">A Terminal Services session identifier. To indicate the session in which the calling application is running
/// (or the current session) specify <see cref="WTS_CURRENT_SESSION"/>. Only specify <see cref="WTS_CURRENT_SESSION"/> when obtaining session information on the
/// local server. If it is specified when querying session information on a remote server, the returned session
/// information will be inconsistent. Do not use the returned data in this situation.</param>
/// <param name="wtsInfoClass">Specifies the type of information to retrieve. This parameter can be one of the values from the <see cref="WTSInfoClass"/> enumeration type. </param>
/// <param name="ppBuffer">Pointer to a variable that receives a pointer to the requested information. The format and contents of the data depend on the information class specified in the <see cref="WTSInfoClass"/> parameter.
/// To free the returned buffer, call the <see cref="WTSFreeMemory"/> function. </param>
/// <param name="pBytesReturned">Pointer to a variable that receives the size, in bytes, of the data returned in ppBuffer.</param>
/// <returns>If the function succeeds, the return value is a nonzero value.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
[DllImport("Wtsapi32.dll")]
public static extern bool WTSQuerySessionInformation(
    System.IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);

VB .NET Signature:

    Private Declare Auto Function WTSQuerySessionInformation Lib "wtsapi32.dll" ( _
     ByVal hServer As Int32, _
     ByVal SessionId As Int32, _
     ByVal InfoClass As WTS_INFO_CLASS, _
     ByRef ppBuffer As IntPtr, _
     ByRef pCount As Int32) As Int32

User-Defined Types:

WTSInfoClass

Structure:

WTS_CLIENT_ADDRESS

Notes:

Used in conjunction with WTSGetActiveConsoleSessionId and WTSFreeMemory.

Tips & Tricks:

Please add some!

How to retrieve username by session id:

    [DllImport("Wtsapi32.dll")]
    private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out int pBytesReturned);

    [DllImport("Wtsapi32.dll")]
    private static extern void WTSFreeMemory(IntPtr pointer);

    public static String GetUsernameBySessionId(int sessionId)
    {
        IntPtr buffer;
        int strLen;
        var username = "SYSTEM"; // assume SYSTEM as this will return "\0" below
        if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLASS.WTSUserName, out buffer, out strLen) && strLen > 1)
        {
        username = Marshal.PtrToStringAnsi(buffer); // don't need length as these are null terminated strings
        WTSFreeMemory(buffer);
        if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLASS.WTSDomainName, out buffer, out strLen) && strLen > 1)
        {
            username = Marshal.PtrToStringAnsi(buffer)+"\\"+username; // prepend domain name
            WTSFreeMemory(buffer);
        }
        }
        return username;
    }

Sample Code:

    using System;
    using System.Runtime.InteropServices;

    namespace TerminalServer
    {
        /// <summary>
        /// Static helper methods.
        /// </summary>
        internal class Utilities
        {
    /// <summary>
    /// The WTSQuerySessionInformation function retrieves session information for the specified
    /// session on the specified terminal server.
    /// It can be used to query session information on local and remote terminal servers.
    /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/termserv/termserv/wtsquerysessioninformation.asp
    /// </summary>
    /// <param name="hServer">Handle to a terminal server. Specify a handle opened by the WTSOpenServer function,
    /// or specify <see cref="WTS_CURRENT_SERVER_HANDLE"/> to indicate the terminal server on which your application is running.</param>
    /// <param name="sessionId">A Terminal Services session identifier. To indicate the session in which the calling application is running
    /// (or the current session) specify <see cref="WTS_CURRENT_SESSION"/>. Only specify <see cref="WTS_CURRENT_SESSION"/> when obtaining session information on the
    /// local server. If it is specified when querying session information on a remote server, the returned session
    /// information will be inconsistent. Do not use the returned data in this situation.</param>
    /// <param name="wtsInfoClass">Specifies the type of information to retrieve. This parameter can be one of the values from the <see cref="WTSInfoClass"/> enumeration type. </param>
    /// <param name="ppBuffer">Pointer to a variable that receives a pointer to the requested information. The format and contents of the data depend on the information class specified in the <see cref="WTSInfoClass"/> parameter.
    /// To free the returned buffer, call the <see cref="WTSFreeMemory"/> function. </param>
    /// <param name="pBytesReturned">Pointer to a variable that receives the size, in bytes, of the data returned in ppBuffer.</param>
    /// <returns>If the function succeeds, the return value is a nonzero value.
    /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
    /// </returns>
            [DllImport("Wtsapi32.dll")]
            public static extern bool WTSQuerySessionInformation(
                System.IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);

            // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/termserv/termserv/wtsgetactiveconsolesessionid.asp
            /// <summary>
            /// The WTSGetActiveConsoleSessionId function retrieves the
            /// Terminal Services session currently attached to the physical console.
            /// The physical console is the monitor, keyboard, and mouse.
            /// </summary>
            /// <returns>An <see cref="int"/> equal to 0 indicates that the current session is attached to the physical console.</returns>
            /// <remarks>It is not necessary that Terminal Services be running for this function to succeed.</remarks>
            [DllImport("Kernel32.dll")]
            public static extern int WTSGetActiveConsoleSessionId();

            /// <summary>
            /// The WTSFreeMemory function frees memory allocated by a Terminal Services function.
            /// </summary>
            /// <param name="memory">Pointer to the memory to free.</param>
            [DllImport("wtsapi32.dll", ExactSpelling=true, SetLastError=false)]
            public static extern void WTSFreeMemory( IntPtr memory );

            public const int WTS_CURRENT_SESSION = -1;

            /// <summary>
            /// Gets a <see cref="bool"/> indicating if the current ehmsas.exe is being run locally or in a Remote session.
            /// </summary>
            /// <returns>Returns true if the process is being executed locally or from a Terminal Server session.</returns>
            internal static bool GetIsRunningLocally()
            {
                System.IntPtr buffer = IntPtr.Zero;
                uint bytesReturned;

                int sessionID;

                try
                {
                    bool sessionInfo = WTSQuerySessionInformation( System.IntPtr.Zero, WTS_CURRENT_SESSION, WTSInfoClass.WTSSessionId, out buffer, out bytesReturned );
                    sessionID = Marshal.ReadInt32( buffer );

                }
                catch
                {
                    return true;
                }
                finally
                {
                    WTSFreeMemory( buffer );
                    buffer = IntPtr.Zero;
                }

                int currentSessionId = WTSGetActiveConsoleSessionId();

                if (currentSessionId == sessionID)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }

Alternative Managed API:

TODO

Documentation