/// <summary> /// Read all session info running on the system. /// </summary> /// <param name="RdpOnly">If set to <see langword="true"/>, then only Rdp sessions /// will be listed; otherwise, all session types <see cref="T:Oerlikon.Balzers.Rdp.Interfaces.WTS_CLIENT_PROTOCOL_TYPE"/> .</param> public List <TerminalSessionInfo> ListSessions(bool RdpOnly) { IntPtr server = IntPtr.Zero; List <TerminalSessionInfo> ret = new List <TerminalSessionInfo>(); //server = OpenServer(this.m_ServerName); try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 count = 0; Int32 retval = WTSEnumerateSessions(this.hServ, 0, 1, ref ppSessionInfo, ref count); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int64 current = (int)ppSessionInfo; if (retval != 0) { for (int i = 0; i < count; i++) { TerminalSessionInfo tsi = GetSessionInfo(this.hServ, (System.IntPtr)current); current += dataSize; if (tsi.ProtocolType == WTS_CLIENT_PROTOCOL_TYPE.RDP || !RdpOnly) { ret.Add(tsi); } } WTSFreeMemory(ppSessionInfo); } } finally { //CloseServer(server); } return(ret); }
public static TerminalSessionInfo[] GetUserSessionInfo(string ServerName) { if (ServerName == "localhost" || ServerName == String.Empty) { ServerName = Environment.MachineName; } // Find and get detailed information for all user sessions // Also determine the active user session. If a console user exists, then that will be the active user session. // If no console user exists but users are logged in, such as on terminal servers, then select the first logged-in non-console user that is either 'Active' or 'Connected' as the active user. TerminalSessionData[] sessions = ListSessions(ServerName); TerminalSessionInfo sessionInfo = new TerminalSessionInfo(); List <TerminalSessionInfo> userSessionsInfo = new List <TerminalSessionInfo>(); string firstActiveUserNTAccount = String.Empty; bool IsActiveUserSessionSet = false; foreach (TerminalSessionData session in sessions) { if (session.IsUserSession == true) { sessionInfo = GetSessionInfo(ServerName, session.SessionId); if (sessionInfo.IsUserSession == true) { if ((firstActiveUserNTAccount == String.Empty) && (sessionInfo.ConnectState == "Active" || sessionInfo.ConnectState == "Connected")) { firstActiveUserNTAccount = sessionInfo.NTAccount; } if (sessionInfo.IsConsoleSession == true) { sessionInfo.IsActiveUserSession = true; IsActiveUserSessionSet = true; } else { sessionInfo.IsActiveUserSession = false; } userSessionsInfo.Add(sessionInfo); } } } TerminalSessionInfo[] userSessions = userSessionsInfo.ToArray(); if (IsActiveUserSessionSet == false) { foreach (TerminalSessionInfo userSession in userSessions) { if (userSession.NTAccount == firstActiveUserNTAccount) { userSession.IsActiveUserSession = true; break; } } } return(userSessions); }
public static TerminalSessionInfo[] GetUserSessionInfo(string ServerName) { if (ServerName == "localhost" || ServerName == String.Empty) { ServerName = Environment.MachineName; } TerminalSessionData[] sessions = ListSessions(ServerName); TerminalSessionInfo sessionInfo = new TerminalSessionInfo(); List <TerminalSessionInfo> userSessionsInfo = new List <TerminalSessionInfo>(); string firstActiveUserNTAccount = String.Empty; bool IsActiveUserSessionSet = false; foreach (TerminalSessionData session in sessions) { if (session.IsUserSession == true) { sessionInfo = GetSessionInfo(ServerName, session.SessionId); if (sessionInfo.IsUserSession == true) { if ((firstActiveUserNTAccount == String.Empty) && (sessionInfo.ConnectState == "Active" || sessionInfo.ConnectState == "Connected")) { firstActiveUserNTAccount = sessionInfo.NTAccount; } if (sessionInfo.IsConsoleSession == true) { sessionInfo.IsActiveUserSession = true; IsActiveUserSessionSet = true; } else { sessionInfo.IsActiveUserSession = false; } userSessionsInfo.Add(sessionInfo); } } } TerminalSessionInfo[] userSessions = userSessionsInfo.ToArray(); if (IsActiveUserSessionSet == false) { foreach (TerminalSessionInfo userSession in userSessions) { if (userSession.NTAccount == firstActiveUserNTAccount) { userSession.IsActiveUserSession = true; break; } } } return(userSessions); }
private TerminalSessionInfo GetChangedTerminalSession(List <TerminalSessionInfo> oldSessions, List <TerminalSessionInfo> newSessions, out WM_WTSSESSION_CHANGE_TYPE sessionChangeType) { TerminalSessionInfo retval = new TerminalSessionInfo(0); sessionChangeType = (WM_WTSSESSION_CHANGE_TYPE)0; // session added if (newSessions.Count > oldSessions.Count) { retval = newSessions.Where(s => oldSessions.Where(old => old.SessionInfo.iSessionID == s.SessionInfo.iSessionID).ToList().Count == 0).FirstOrDefault(); if (retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSConnected || retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSActive || retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSConnectQuery) { sessionChangeType = (retval.ProtocolType == WTS_CLIENT_PROTOCOL_TYPE.RDP) ? WM_WTSSESSION_CHANGE_TYPE.WTS_REMOTE_CONNECT : WM_WTSSESSION_CHANGE_TYPE.WTS_CONSOLE_CONNECT; } } else if (newSessions.Count < oldSessions.Count) { retval = oldSessions.Where(s => newSessions.Where(old => old.SessionInfo.iSessionID == s.SessionInfo.iSessionID).ToList().Count == 0).FirstOrDefault(); retval.SessionInfo.oState = WTS_CONNECTSTATE_CLASS.WTSDisconnected; retval.WtsInfo.State = WTS_CONNECTSTATE_CLASS.WTSDisconnected; sessionChangeType = (retval.ProtocolType == WTS_CLIENT_PROTOCOL_TYPE.RDP) ? WM_WTSSESSION_CHANGE_TYPE.WTS_REMOTE_DISCONNECT : WM_WTSSESSION_CHANGE_TYPE.WTS_CONSOLE_DISCONNECT; } else { retval = newSessions.Where(s => oldSessions.Where(old => old.SessionInfo.iSessionID == s.SessionInfo.iSessionID && old.SessionInfo.oState != s.SessionInfo.oState).ToList().Count > 0 && s.SessionInfo.iSessionID != 0).FirstOrDefault(); if (retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSConnected || retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSActive || retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSConnectQuery) { sessionChangeType = (retval.ProtocolType == WTS_CLIENT_PROTOCOL_TYPE.RDP) ? WM_WTSSESSION_CHANGE_TYPE.WTS_REMOTE_CONNECT : WM_WTSSESSION_CHANGE_TYPE.WTS_CONSOLE_CONNECT; } else if (retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSDisconnected || retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSDown || retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSIdle || retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSListen || retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSReset || retval.SessionInfo.oState == WTS_CONNECTSTATE_CLASS.WTSShadow) { sessionChangeType = (retval.ProtocolType == WTS_CLIENT_PROTOCOL_TYPE.RDP) ? WM_WTSSESSION_CHANGE_TYPE.WTS_REMOTE_DISCONNECT : WM_WTSSESSION_CHANGE_TYPE.WTS_CONSOLE_DISCONNECT; } } return(retval); }
public static TerminalSessionInfo GetSessionInfo(string ServerName, int SessionId) { IntPtr server = IntPtr.Zero; IntPtr buffer = IntPtr.Zero; int bytesReturned; TerminalSessionInfo data = new TerminalSessionInfo(); bool _IsCurrentSessionId = false; bool _IsConsoleSession = false; bool _IsUserSession = false; int currentSessionID = 0; string _NTAccount = String.Empty; if (ServerName == "localhost" || ServerName == String.Empty) { ServerName = Environment.MachineName; } if (ProcessIdToSessionId(GetCurrentProcessId(), ref currentSessionID) == false) { currentSessionID = -1; } // Get all members of the local administrators group bool _IsLocalAdminCheckSuccess = false; List <string> localAdminGroupSidsList = new List <string>(); try { DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + ServerName + ",Computer"); string localAdminGroupName = new SecurityIdentifier("S-1-5-32-544").Translate(typeof(NTAccount)).Value.Split('\\')[1]; DirectoryEntry admGroup = localMachine.Children.Find(localAdminGroupName, "group"); object members = admGroup.Invoke("members", null); foreach (object groupMember in (IEnumerable)members) { DirectoryEntry member = new DirectoryEntry(groupMember); if (member.Name != String.Empty) { localAdminGroupSidsList.Add((new NTAccount(member.Name)).Translate(typeof(SecurityIdentifier)).Value); } } _IsLocalAdminCheckSuccess = true; } catch { } try { server = OpenServer(ServerName); if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientBuildNumber, out buffer, out bytesReturned) == false) { return(data); } int lData = Marshal.ReadInt32(buffer); data.ClientBuildNumber = lData; if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientDirectory, out buffer, out bytesReturned) == false) { return(data); } string strData = Marshal.PtrToStringAnsi(buffer); data.ClientDirectory = strData; if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientName, out buffer, out bytesReturned) == false) { return(data); } strData = Marshal.PtrToStringAnsi(buffer); data.ClientName = strData; if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientProtocolType, out buffer, out bytesReturned) == false) { return(data); } Int16 intData = Marshal.ReadInt16(buffer); if (intData == 2) { strData = "RDP"; data.IsRdpSession = true; } else { strData = ""; data.IsRdpSession = false; } data.ClientProtocolType = strData; if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ConnectState, out buffer, out bytesReturned) == false) { return(data); } lData = Marshal.ReadInt32(buffer); data.ConnectState = ((WTS_CONNECTSTATE_CLASS)lData).ToString(); if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.SessionId, out buffer, out bytesReturned) == false) { return(data); } lData = Marshal.ReadInt32(buffer); data.SessionId = lData; if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.DomainName, out buffer, out bytesReturned) == false) { return(data); } strData = Marshal.PtrToStringAnsi(buffer).ToUpper(); data.DomainName = strData; if (strData != String.Empty) { _NTAccount = strData; } if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.UserName, out buffer, out bytesReturned) == false) { return(data); } strData = Marshal.PtrToStringAnsi(buffer); data.UserName = strData; if (strData != String.Empty) { data.NTAccount = _NTAccount + "\\" + strData; string _Sid = (new NTAccount(_NTAccount + "\\" + strData)).Translate(typeof(SecurityIdentifier)).Value; data.SID = _Sid; if (_IsLocalAdminCheckSuccess == true) { foreach (string localAdminGroupSid in localAdminGroupSidsList) { if (localAdminGroupSid == _Sid) { data.IsLocalAdmin = true; break; } else { data.IsLocalAdmin = false; } } } } if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.SessionName, out buffer, out bytesReturned) == false) { return(data); } strData = Marshal.PtrToStringAnsi(buffer); data.SessionName = strData; if (strData != "Services" && strData != "RDP-Tcp" && data.UserName != String.Empty) { _IsUserSession = true; } data.IsUserSession = _IsUserSession; if (strData == "Console") { _IsConsoleSession = true; } data.IsConsoleSession = _IsConsoleSession; WINSTATIONINFORMATIONW wsInfo = GetWinStationInformation(server, SessionId); DateTime?_loginTime = FileTimeToDateTime(wsInfo.LoginTime); DateTime?_lastInputTime = FileTimeToDateTime(wsInfo.LastInputTime); DateTime?_disconnectTime = FileTimeToDateTime(wsInfo.DisconnectTime); DateTime?_currentTime = FileTimeToDateTime(wsInfo.CurrentTime); TimeSpan?_idleTime = (_currentTime != null && _lastInputTime != null) ? _currentTime.Value - _lastInputTime.Value : TimeSpan.Zero; data.LogonTime = _loginTime; data.IdleTime = _idleTime; data.DisconnectTime = _disconnectTime; if (currentSessionID == SessionId) { _IsCurrentSessionId = true; } data.IsCurrentSession = _IsCurrentSessionId; } finally { WTSFreeMemory(buffer); buffer = IntPtr.Zero; CloseServer(server); } return(data); }
public static TerminalSessionInfo GetSessionInfo(string ServerName, int SessionId) { IntPtr server = IntPtr.Zero; server = OpenServer(ServerName); System.IntPtr buffer = IntPtr.Zero; uint bytesReturned; TerminalSessionInfo data = new TerminalSessionInfo(); try { bool worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ApplicationName, out buffer, out bytesReturned); if (!worked) { return(data); } string strData = Marshal.PtrToStringAnsi(buffer); data.ApplicationName = strData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientAddress, out buffer, out bytesReturned); if (!worked) { return(data); } WTS_CLIENT_ADDRESS si = (WTS_CLIENT_ADDRESS)Marshal.PtrToStructure((System.IntPtr)buffer, typeof(WTS_CLIENT_ADDRESS)); data.ClientAddress = si; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientBuildNumber, out buffer, out bytesReturned); if (!worked) { return(data); } int lData = Marshal.ReadInt32(buffer); data.ClientBuildNumber = lData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientDirectory, out buffer, out bytesReturned); if (!worked) { return(data); } strData = Marshal.PtrToStringAnsi(buffer); data.ClientDirectory = strData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientDisplay, out buffer, out bytesReturned); if (!worked) { return(data); } WTS_CLIENT_DISPLAY cd = (WTS_CLIENT_DISPLAY)Marshal.PtrToStructure((System.IntPtr)buffer, typeof(WTS_CLIENT_DISPLAY)); data.ClientDisplay = cd; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientHardwareId, out buffer, out bytesReturned); if (!worked) { return(data); } lData = Marshal.ReadInt32(buffer); data.ClientHardwareId = lData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientName, out buffer, out bytesReturned); strData = Marshal.PtrToStringAnsi(buffer); data.ClientName = strData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientProductId, out buffer, out bytesReturned); Int16 intData = Marshal.ReadInt16(buffer); data.ClientProductId = intData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientProtocolType, out buffer, out bytesReturned); intData = Marshal.ReadInt16(buffer); data.ClientProtocolType = intData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ConnectState, out buffer, out bytesReturned); lData = Marshal.ReadInt32(buffer); data.ConnectState = (WTS_CONNECTSTATE_CLASS)Enum.ToObject(typeof(WTS_CONNECTSTATE_CLASS), lData); worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.DomainName, out buffer, out bytesReturned); strData = Marshal.PtrToStringAnsi(buffer); data.DomainName = strData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.InitialProgram, out buffer, out bytesReturned); strData = Marshal.PtrToStringAnsi(buffer); data.InitialProgram = strData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.OEMId, out buffer, out bytesReturned); strData = Marshal.PtrToStringAnsi(buffer); data.OEMId = strData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.SessionId, out buffer, out bytesReturned); lData = Marshal.ReadInt32(buffer); data.SessionId = lData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.UserName, out buffer, out bytesReturned); strData = Marshal.PtrToStringAnsi(buffer); data.UserName = strData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.WinStationName, out buffer, out bytesReturned); strData = Marshal.PtrToStringAnsi(buffer); data.WinStationName = strData; worked = WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.WorkingDirectory, out buffer, out bytesReturned); strData = Marshal.PtrToStringAnsi(buffer); data.WorkingDirectory = strData; } finally { WTSFreeMemory(buffer); buffer = IntPtr.Zero; CloseServer(server); } return(data); }
/// <param name="pServer"></param> /// <param name="pSessionInfo"></param> private TerminalSessionInfo GetSessionInfo(IntPtr pServer, IntPtr pSessionInfo) { int iCurrent = (int)pSessionInfo; uint iReturned = 0; WTS_CLIENT_ADDRESS oClientAddres = new WTS_CLIENT_ADDRESS(); WTS_CLIENT_DISPLAY oClientDisplay = new WTS_CLIENT_DISPLAY(); WTS_CLIENT_PROTOCOL_TYPE oClientProtocol = WTS_CLIENT_PROTOCOL_TYPE.UNKNOWN; WTS_CLIENT_INFO oClientInfo = new WTS_CLIENT_INFO(); WTSINFO oWtsInfo = new WTSINFO(); string sIPAddress = string.Empty; string sUserName = string.Empty, sClientName = string.Empty; string sDomain = string.Empty; string sClientApplicationDirectory = string.Empty; TerminalSessionInfo retval = new TerminalSessionInfo(0); // Get session info structure WTS_SESSION_INFO oSessionInfo = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)iCurrent, typeof(WTS_SESSION_INFO)); //Get the IP address of the Terminal Services User IntPtr pAddress = IntPtr.Zero; if (WTSQuerySessionInformation(pServer, oSessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientAddress, out pAddress, out iReturned) == true) { oClientAddres = (WTS_CLIENT_ADDRESS)Marshal.PtrToStructure(pAddress, oClientAddres.GetType()); sIPAddress = oClientAddres.bAddress[2] + "." + oClientAddres.bAddress[3] + "." + oClientAddres.bAddress[4] + "." + oClientAddres.bAddress[5]; } //Get the User Name of the Terminal Services User if (WTSQuerySessionInformation(pServer, oSessionInfo.iSessionID, WTS_INFO_CLASS.WTSUserName, out pAddress, out iReturned) == true) { sUserName = Marshal.PtrToStringAnsi(pAddress); } //Get the Client Name of the Terminal Services User if (WTSQuerySessionInformation(pServer, oSessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientName, out pAddress, out iReturned) == true) { sClientName = Marshal.PtrToStringAnsi(pAddress); } //Get the Domain Name of the Terminal Services User if (WTSQuerySessionInformation(pServer, oSessionInfo.iSessionID, WTS_INFO_CLASS.WTSDomainName, out pAddress, out iReturned) == true) { sDomain = Marshal.PtrToStringAnsi(pAddress); } //Get the Display Information of the Terminal Services User if (WTSQuerySessionInformation(pServer, oSessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientDisplay, out pAddress, out iReturned) == true) { oClientDisplay = (WTS_CLIENT_DISPLAY)Marshal.PtrToStructure(pAddress, oClientDisplay.GetType()); } //Get the Application Directory of the Terminal Services User if (WTSQuerySessionInformation(pServer, oSessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientDirectory, out pAddress, out iReturned) == true) { sClientApplicationDirectory = Marshal.PtrToStringAnsi(pAddress); } //Get protocol type if (WTSQuerySessionInformation(pServer, oSessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientProtocolType, out pAddress, out iReturned) == true) { oClientProtocol = (WTS_CLIENT_PROTOCOL_TYPE)Marshal.ReadInt16(pAddress); } //Get client info if (WTSQuerySessionInformation(pServer, oSessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientInfo, out pAddress, out iReturned) == true) { oClientInfo = (WTS_CLIENT_INFO)Marshal.PtrToStructure(pAddress, oClientInfo.GetType()); //sUserName = String.IsNullOrEmpty(sUserName) ? oClientInfo.UserName : sUserName; } //Get WTS info if (WTSQuerySessionInformation(pServer, oSessionInfo.iSessionID, WTS_INFO_CLASS.WTSSessionInfo, out pAddress, out iReturned) == true) { oWtsInfo = (WTSINFO)Marshal.PtrToStructure(pAddress, oWtsInfo.GetType()); } // fill result retval.SessionInfo = oSessionInfo; //retval.SessionInfo.oState = oSessionInfo.oState; //retval.SessionInfo.sWinsWorkstationName = oSessionInfo.sWinsWorkstationName == null ? "" : oSessionInfo.sWinsWorkstationName; retval.UserName = sUserName == null ? "" : sUserName; retval.ClientMachineName = sClientName == null ? "" : sClientName; retval.ClientIPAddress = sIPAddress == null ? "" : sIPAddress; retval.Domain = sDomain == null ? "" : sDomain; retval.ProtocolType = oClientProtocol; retval.ClientInfo = oClientInfo; retval.WtsInfo = oWtsInfo; return(retval); }