using Microsoft.Win32;
public class App
{
static void Main()
{
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
Console.ReadLine();
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if(e.Reason == SessionSwitchReason.SessionLock)
{
Console.WriteLine("locked at {0}", DateTime.Now);
}
if(e.Reason == SessionSwitchReason.SessionUnlock)
{
Console.WriteLine("unlocked at {0}", DateTime.Now);
}
}
I have created a Windows service. When I restart the system and login, logoff, lock or unlock the session. it will not capture the event. The service is running, but it will not work properly.
When i restart the service it will capture all events as expected. How do I go about troubleshooting/fixing this?
Make your service dependent on TermService (the Terminal Services service). Under the covers, the SystemEvents class is based on the WTSRegisterSessionNotification Win32 function, which is documented to fail if the Terminal Services service hasn't started by the time it's called. By adding the dependency on TermService to your service, that won't happen. You could also connect to the Global\TermSrvReadyEvent global event using a technique like this and wait to register the SystemEvent handler until the TS "ready" event fires.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With