Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if no user is currently logged on to Windows

I'm writing a Windows Service application which listens for connections and performs certain tasks as instructed from a different application running on another computer on the network.

One of the tasks ensures no user is currently logged on, locks the workstation, delete some files, and then restarts the system. I considered using this solution to look through the list of running processes and check the user names, determining if no user is logged on by matchhing the user names against SYSTEM, NETWORK, etc. I realized I have PostgreSQL running which uses a user account named postgres so that wouldn't work. Checking if explorer.exe is running also wouldn't work because explorer sometmes crashes, or I sometimes end the process myself and restart it.

What would be a good way of determining that NO user is logged on to a workstation using C#?

like image 718
Zahymaka Avatar asked Feb 15 '09 19:02

Zahymaka


People also ask

How do I see all users on Windows 10 login screen?

To display all local user accounts on the Windows login screen, you need to change the value of Enabled parameter to 1 in the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\UserSwitch.

Is someone logged into my computer?

To see all the login activities on your PC, use Windows Event Viewer. This tool will show you all Windows services that have been accessed and logins, errors and warnings. To access the Windows Event Viewer, click the search icon and type in Event Viewer. Click Windows Logs, then choose Security.


3 Answers

Use WTSGetActiveConsoleSessionId() to determine whether anybody is logged on locally. Use WTSEnumerateSessions() to determine if there is any session at all (including remote terminal services sessions).

like image 136
flodin Avatar answered Oct 02 '22 14:10

flodin


You tried to check whether explorer.exe is running or not. Why not go for the winlogon.exe process?

public bool isLoggedOn()
{
    Process[] pname = Process.GetProcessesByName("winlogon");
    if (pname.Length == 0)
        return false;
    else
        return true;
}
like image 43
libjup Avatar answered Oct 02 '22 13:10

libjup


Another option, if you don't want to deal with the P/Invokes: use Cassia.

using Cassia;

public static bool IsSomeoneLoggedOn(string server)
{
    foreach (ITerminalServicesSession session in new TerminalServicesManager().GetSessions(server))
    {
        if (!string.IsNullOrEmpty(session.UserName))
        {
            return true;
        }
    }
    return false;
}
like image 38
Dan Ports Avatar answered Oct 02 '22 13:10

Dan Ports