Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

WTSQuerySessionInformation (wtsapi32)
 
.
Summary
TODO - 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

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

Notes:

Used in conjunction with WTSGetActiveConsoleSessionId and WTSFreeMemory.

Tips & Tricks:

Please add some!

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_SERVER_HANDLE = -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_SERVER_HANDLE, 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;
                }
            }

// From here new code added (sorry, but I haven't enough time to explain it, it's 09:20 pm and I want to go home!)

// If doubts or suggestion please feel free to mail me: kiwisuperpower@hotmail.com

        [StructLayout(LayoutKind.Sequential)]
        public struct WtsClientAddress
        {
            public int AddressFamily;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst=20)]
            public byte[] Address;
        }

        public enum WTSInfoClass
        {
            WTSInitialProgram,
            WTSApplicationName,
            WTSWorkingDirectory,
            WTSOEMId,
            WTSSessionId,
            WTSUserName,
            WTSWinStationName,
            WTSDomainName,
            WTSConnectState,
            WTSClientBuildNumber,
            WTSClientName,
            WTSClientDirectory,
            WTSClientProductId,
            WTSClientHardwareId,
            WTSClientAddress,
            WTSClientDisplay,
            WTSClientProtocolType
        };

        // This simple property returns the IP of a client connected throught TS Services
        public static System.Net.IPAddress ClientIP
        {
            get
            {
                System.IntPtr buffer;
                uint bytesReturned;
                bool sessionInfo= WTSQuerySessionInformation(CWTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSInfoClass.WTSClientAddress, out buffer, out bytesReturned);
                WtsClientAddress stCA= (WtsClientAddress)Marshal.PtrToStructure(buffer, typeof(WtsClientAddress));
                string sIP= stCA.Address[2].ToString() + "." + stCA.Address[3].ToString() + "." + stCA.Address[4].ToString() + "." + stCA.Address[5].ToString();

                return System.Net.IPAddress.Parse(sIP);
            }
        }

        }
    }

Alternative Managed API:

TODO

Documentation

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Find References
Show Printable Version
Revisions