简体   繁体   中英

How to reliably capture Windows logon, logoff, lock and unlock events from a service?

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.

尝试保留事件的注册状态,而不是在readline之后将其删除。您正在注册以侦听,然后立即取消注册,这没有任何意义。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM