Determine if anyone is logged onto a remote computer.
Determining if someone is logged into a remote computer, either interactively or remotely, is not as easy as it sounds. A quick solution however is to merely enumerate the explorer.exe process (which wont’ be running if nobody is logged in):
public static bool isAnyoneLoggedOn(string computer_name)
{
Console.Write("Looking for users on " + computer_name + "... ");
try
{
ConnectionOptions oConn = new ConnectionOptions();
System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\" + computer_name + "\\root\\cimv2", oConn);
//get explorer.exe process instances
System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("Select * from Win32_Process Where Name = 'explorer.exe'");
//Execute the query
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
//Get the results
ManagementObjectCollection oReturnCollection = oSearcher.Get();
if (oReturnCollection.Count == 0)
{
Console.WriteLine("No Users.");
return false;
}
else
{
Console.WriteLine("Found User.");
return true;
}
}
catch (Exception M)
{
// Probably an access denied error. In my case I must assume someone is logged in.
string errorMessage = "Error in isAnyoneLoggedOn() on " + computer_name + ": " + M.Message;
Console.WriteLine(errorMessage);
return true;
}
}


