2009-06-15 136 views
0

我想知道如何檢索登錄的用戶列表。我可以打開Windows任務管理器並查看用戶選項卡並查看在PC上登錄的用戶。我如何獲得該用戶列表。謝謝。C# - 登錄會話列表

回答

1

看看WMI。您可以使用System.Management命名空間:

System.Management.ConnectionOptions myConnectionOptions = new System.Management.ConnectionOptions(); 
     myConnectionOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate; 

    System.Management.ManagementScope objwmiservice; 
    System.Management.ManagementObjectSearcher myObjectSearcher; 
    System.Management.ManagementObjectCollection myCollection; 

    try 
    { 
     objwmiservice = new System.Management.ManagementScope(("\\\\" + (HostOrIP + "\\root\\cimv2")), myConnectionOptions); 
     objwmiservice.Connect(); 
     myObjectSearcher = new System.Management.ManagementObjectSearcher(objwmiservice.Path.ToString(), "Select UserName from Win32_ComputerSystem"); 
     myObjectSearcher.Options.Timeout = new TimeSpan(0, 0, 0, 0, 7000); 
     myCollection = myObjectSearcher.Get(); 

     foreach (System.Management.ManagementObject myObject in myCollection) 
     { 
      if (!(myObject.GetPropertyValue("User name") == null)) 
      { 
       string Userx = myObject.GetPropertyValue("Usernam e").ToString(); 
       int posx = Userx.LastIndexOf("\\"); 
       if ((posx > 0)) 
       { 
        Userx = Userx.Substring((posx + 1)); 
        return Userx.ToUpper(); 
       } 
      } 
     } 
     return "<Nobody>"; 
    } 
    catch (Exception) 
    { 
      return "<Nobody>"; 
    } 
} 

這是我從this link

+0

謝謝了。當我使用快速用戶切換並且有多個登錄時,這隻會返回一個用戶,並且這是活動的。 – James 2009-06-15 17:01:46