Using C# how to get a list of logged in users to Windows

Kamalpreet Singh 81 Reputation points
2021-04-09T22:35:34.107+00:00

How can we get a list of users who are logged in to Windows whether Disconnected or Connected?

Basically, I want to get a list of users similar to what we see on Task Manager.
This list should not include usernames under whom only a process or a service is running. I'm looking to fetch real users logged in to Windows machine.

This is what I came up with however it is returning the logged out users as well:

public bool GetLogonUser()
{
    string query = "Select * from Win32_LogonSession Where LogonType = 2";
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    ManagementObjectCollection processList = searcher.Get();

    foreach (ManagementObject obj in processList)
    {
        string query_ua = "ASSOCIATORS OF {Win32_LogonSession.LogonId=" + obj["LogonId"] + "} WHERE AssocClass=Win32_LoggedOnUser Role=Dependent";
        ManagementObjectSearcher searcher_ua = new ManagementObjectSearcher(query_ua);
        ManagementObjectCollection processList_ua = searcher_ua.Get();

        try
        {
            foreach (ManagementObject associator in processList_ua)
            {
                string Name = associator["Name"]?.ToString();
                Console.WriteLine(Name);
                if (Name.ToLower().EndsWith(Application.ProcessUserName.ToLower()))
                {
                    return true;
                }
            }
        }
        catch (Exception ex)
        {
            continue;
        }
    }

    return false;
}
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,521 Reputation points
    2021-04-10T10:51:39.253+00:00

    Task Manager does not use WMI
    You can use similar APIs like WTS APIs

    A test on Windows 10 (maybe change the test on si.State) =>

    IntPtr pSessions = IntPtr.Zero;
    int nSessions;
    if (WTSEnumerateSessions((IntPtr)WTS_CURRENT_SERVER_HANDLE, 0, 1, out pSessions, out nSessions))
    {
        int nDataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
        IntPtr pCurrentSession = pSessions;
        for (int Index = 0; Index < nSessions; Index++)
        {
            WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure(pCurrentSession, typeof(WTS_SESSION_INFO));
            if (si.State == WTS_CONNECTSTATE_CLASS.WTSActive || si.State == WTS_CONNECTSTATE_CLASS.WTSConnected)
            {
                uint nBytesReturned = 0;
                IntPtr pUserName = IntPtr.Zero;
                bool bRet = WTSQuerySessionInformation((IntPtr)WTS_CURRENT_SERVER_HANDLE, si.SessionId, WTS_INFO_CLASS.WTSUserName, out pUserName, out nBytesReturned);
                string sUserName = Marshal.PtrToStringUni(pUserName);
                Console.WriteLine("User Name: {0}", sUserName);
            }    
            pCurrentSession += nDataSize;
        }
        WTSFreeMemory(pSessions);
    }
    

    Declarations =>

        public const int WTS_CURRENT_SERVER_HANDLE = 0;                                                                                                                                                       
        public const int WTS_CURRENT_SESSION = -1;                                                                                                                                                            
    
        [DllImport("WTSApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]                                                                                                                           
        public static extern bool WTSSendMessage(IntPtr hServer, int SessionId, string pTitle, int TitleLength, string pMessage, int MessageLength, int Style, int Timeout, out int pResponse, Boolean bWait);
    
        [DllImport("WTSApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]                                                                                                                           
        public static extern bool WTSEnumerateSessions(IntPtr hServer, int Reserved, int Version, out IntPtr ppSessionInfo, out int pCount);                                                                  
    
        [DllImport("WTSApi32.dll", SetLastError = true, CharSet = CharSet.Auto)]                                                                                                                              
        public static extern void WTSFreeMemory(IntPtr pMemory);                                                                                                                                              
    
        [DllImport("WTSApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]                                                                                                                           
        public static extern bool WTSQuerySessionInformation(IntPtr hServer, int SessionId, WTS_INFO_CLASS WTSInfoClass, out IntPtr ppBuffer, out uint BytesReturned);                                        
    
        public enum WTS_INFO_CLASS                                                                                                                                                                            
        {                                                                                                                                                                                                     
            WTSInitialProgram,                                                                                                                                                                                
            WTSApplicationName,                                                                                                                                                                               
            WTSWorkingDirectory,                                                                                                                                                                              
            WTSOEMId,                                                                                                                                                                                         
            WTSSessionId,                                                                                                                                                                                     
            WTSUserName,                                                                                                                                                                                      
            WTSWinStationName,                                                                                                                                                                                
            WTSDomainName,                                                                                                                                                                                    
            WTSConnectState,                                                                                                                                                                                  
            WTSClientBuildNumber,                                                                                                                                                                             
            WTSClientName,                                                                                                                                                                                    
            WTSClientDirectory,                                                                                                                                                                               
            WTSClientProductId,                                                                                                                                                                               
            WTSClientHardwareId,                                                                                                                                                                              
            WTSClientAddress,                                                                                                                                                                                 
            WTSClientDisplay,                                                                                                                                                                                 
            WTSClientProtocolType,                                                                                                                                                                            
            WTSIdleTime,                                                                                                                                                                                      
            WTSLogonTime,                                                                                                                                                                                     
            WTSIncomingBytes,                                                                                                                                                                                 
            WTSOutgoingBytes,                                                                                                                                                                                 
            WTSIncomingFrames,                                                                                                                                                                                
            WTSOutgoingFrames,                                                                                                                                                                                
            WTSClientInfo,                                                                                                                                                                                    
            WTSSessionInfo,                                                                                                                                                                                   
            WTSSessionInfoEx,                                                                                                                                                                                 
            WTSConfigInfo,                                                                                                                                                                                    
            WTSValidationInfo,                                                                                                                                                                                
            WTSSessionAddressV4,                                                                                                                                                                              
            WTSIsRemoteSession                                                                                                                                                                                
        }                                                                                                                                                                                                     
    
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]                                                                                                                                      
        public struct WTS_SESSION_INFO                                                                                                                                                                        
        {                                                                                                                                                                                                     
            public int SessionId;             // session id                                                                                                                                                   
            public string pWinStationName;      // name of WinStation this session is connected to                                                                                                            
            public WTS_CONNECTSTATE_CLASS State; // connection state (see enum)                                                                                                                               
        }                                                                                                                                                                                                     
    
        public enum WTS_CONNECTSTATE_CLASS                                                                                                                                                                    
        {                                                                                                                                                                                                     
            WTSActive,              // User logged on to WinStation                                                                                                                                           
            WTSConnected,           // WinStation connected to client                                                                                                                                         
            WTSConnectQuery,        // In the process of connecting to client                                                                                                                                 
            WTSShadow,              // Shadowing another WinStation                                                                                                                                           
            WTSDisconnected,        // WinStation logged on without client                                                                                                                                    
            WTSIdle,                // Waiting for client to connect                                                                                                                                          
            WTSListen,              // WinStation is listening for connection                                                                                                                                 
            WTSReset,               // WinStation is being reset                                                                                                                                              
            WTSDown,                // WinStation is down due to error                                                                                                                                        
            WTSInit,                // WinStation in initialization                                                                                                                                           
        }     
    
    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Duane Arnold 3,216 Reputation points
    2021-04-10T02:01:09.937+00:00

    Well to keep it simple, I would suggest filtering out the logged out users in the list, which you can filter the collection by using Linq.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.