views:

1840

answers:

4

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#?

+10  A: 

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).

flodin
+2  A: 

You could use WMI

select UserName from Win32_ComputerSystem
Alex Reitbort
If someone down-votes this, please provide an explanation as to why. Is the answer wrong? Or are there just better ways to do this?
DOK
+2  A: 

The CodeProject article "Using the Local Security Authority to Enumerate User Sessions in .NET" might be what you are looking for. The code enumerates users and can identify which users (if any) are interactive (i.e., which users are real people).

Snarfblam
+1  A: 

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