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;
}