コード例 #1
0
        public static string GetUsernameFromSessionId(uint sessionId)
        {
            var username = string.Empty;

            if (WTSAPI32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTSAPI32.WTS_INFO_CLASS.WTSUserName,
                                                    out var buffer, out var strLen) && strLen > 1)
            {
                username = Marshal.PtrToStringAnsi(buffer);
                WTSAPI32.WTSFreeMemory(buffer);
            }

            return(username);
        }
コード例 #2
0
        public static List <WindowsSession> GetActiveSessions()
        {
            var sessions         = new List <WindowsSession>();
            var consoleSessionId = Kernel32.WTSGetActiveConsoleSessionId();

            sessions.Add(new WindowsSession
            {
                ID       = consoleSessionId,
                Type     = SessionType.Console,
                Name     = "Console",
                Username = GetUsernameFromSessionId(consoleSessionId)
            });

            var ppSessionInfo     = IntPtr.Zero;
            var count             = 0;
            var enumSessionResult = WTSAPI32.WTSEnumerateSessions(WTSAPI32.WTS_CURRENT_SERVER_HANDLE, 0, 1,
                                                                  ref ppSessionInfo, ref count);
            var dataSize = Marshal.SizeOf(typeof(WTSAPI32.WTS_SESSION_INFO));
            var current  = ppSessionInfo;

            if (enumSessionResult != 0)
            {
                for (var i = 0; i < count; i++)
                {
                    var sessionInfo =
                        (WTSAPI32.WTS_SESSION_INFO)Marshal.PtrToStructure(current, typeof(WTSAPI32.WTS_SESSION_INFO));
                    current += dataSize;
                    if (sessionInfo.State == WTSAPI32.WTS_CONNECTSTATE_CLASS.WTSActive &&
                        sessionInfo.SessionID != consoleSessionId)
                    {
                        sessions.Add(new WindowsSession
                        {
                            ID       = sessionInfo.SessionID,
                            Name     = sessionInfo.pWinStationName,
                            Type     = SessionType.RDP,
                            Username = GetUsernameFromSessionId(sessionInfo.SessionID)
                        });
                    }
                }
            }

            return(sessions);
        }