How to check that no users are logged in with C# on Windows 7?
I'm using C# Windows Forms. Is there an easy way to check if there are no users logged in?
Below is the code I've used for XP, which doesn't seem to work under windows 7 when a user is logged out.
private bool LoggedInUser() { 开发者_JAVA百科 bool loggedIn = true; Process[] aProc = Process.GetProcessesByName("explorer"); if (aProc.Length <= 0) { loggedIn = false; } return loggedIn; }
Thanks :)
[edit]: The program is executed by the task scheduler, not by a user.
You can use the Cassia library to see the active logon sessions.
Enumerating for the explorer.exe
was always flawed, not only in Windows 7. An user session does not necessarily require explorer.exe to be the default shell, so the process named explorer may well be not runnig. And enumerating processes require privileges a normal C# Windows forms application does not held.
The proper way to find user session is to enumerate them via LsaEnumerateLogonSessions
. Another alternative is to use WMI and interogate the Win32_LogonSession
class.
In theory you cannot run a program like that because the program is running and activated while a user is logged in!
Think about the old Windows 2000/XP logging process which uses GINA (Graphical Identification and authentication) in which when the login credentials are verified, it spawns the process Explorer which in turn activates startup and run-once applications upon logging in.
The Login process is now updated and revamped. The only way you can find out about the current sessions is in the unmanaged code perspective, a process that runs before the login credentials dialog box....
You can p/invoke the Win32 API WTSEnumerateSessions / WTSEnumerateSessionsEx to get a listing of all of the current sessions. I think you would only have a session 0 if there are no logged on users on Vista and Win7. A better way to check via this method though is to check the username parameter pUserName
from the Ex variant.
Alternatively (and probably more easily) you could use WTSGetActiveConsoleSessionId and check for a return result or 0xFFFFFFFF
.
//Supported for XP and up
[DllImport("kernel32.dll")]
private static extern uint WTSGetActiveConsoleSessionId();
public static bool HasLoggedInUsers()
{
uint result = WTSGetActiveConsoleSessionId();
return result != 0xFFFFFFFF;
}
精彩评论