question

KamalpreetSingh-1405 avatar image
0 Votes"
KamalpreetSingh-1405 asked KamalpreetSingh-1405 commented

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

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;
 }
dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Castorix31 avatar image
2 Votes"
Castorix31 answered KamalpreetSingh-1405 commented

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                                                                                                                                           
     }     
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered KamalpreetSingh-1405 commented

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.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for your response.
Mind to chime in how can that be done? Sorry I'm newbie with wmi.

0 Votes 0 ·