Session Triggers (Log on/off) in a Windows 7 Service

Feb 2 2018 12:14 PM
The problem I have here might have a quick workaround but I've been stuck for a while.
 
I am writing a service that starts a process when a user logs in and stops it when the user logs out. In my previous tries I have tried using a loop which checked the presence of explorer.exe but it didn't work very well as the infinite loop meant the service was stuck at "starting". So I have looked into the C# on session change. Here is the code I currently have, creating text files to check if it actually works.
  1. public partial class Service1 : ServiceBase  
  2. {  
  3. public Service1()  
  4. {  
  5. InitializeComponent();  
  6. CanPauseAndContinue = true;  
  7. CanHandleSessionChangeEvent = true;  
  8. ServiceName = "Service1";  
  9. }  
  10. public void onDebug()  
  11. {  
  12. OnStart(null);  
  13. }  
  14. protected override void OnSessionChange(SessionChangeDescription changeDescription)  
  15. {  
  16. EventLog.WriteEntry("SimpleService.OnSessionChange", DateTime.Now.ToLongTimeString() +  
  17. " - Session change notice received: " +  
  18. changeDescription.Reason.ToString() + " Session ID: " +  
  19. changeDescription.SessionId.ToString());  
  20. System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "sessionchange.txt");  
  21. switch (changeDescription.Reason)  
  22. {  
  23. case SessionChangeReason.SessionLogon:  
  24. string[] lines = { DateTime.Now.ToShortTimeString() };  
  25. System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "logged in.txt");  
  26. System.IO.File.WriteAllLines(@"C:\Users\Public\test\loggedin.txt", lines);  
  27. break;  
  28. case SessionChangeReason.SessionLogoff:  
  29. string[] lines2 = { DateTime.Now.ToShortTimeString() };  
  30. System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "logged out.txt");  
  31. System.IO.File.WriteAllLines(@"C:\Users\Public\test\loggedout.txt", lines2);  
  32. break;  
  33. }  
  34. }  
  35. protected override void OnStart(string[] args)  
  36. {  
  37. System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "onstart.txt");  
  38. }  
I expected this to work, but apparently not. The on start text file is being created, but out of the 4 logged on/off ones that should appear (somewhere) only loggedout.txt appears in the Public user directory after a log out. No matter how many times I shut down, log in or out the other text files for login are not being created. The time in the only loggedout.txt file create also won't update.
 
If it helps, I'm running this in a Virtual Machine. I have also read somewhere that SessionChange might only apply to remote log ins but I'm not sure. I'm not sure how to proceed, wether to keep trying or there is another way for services to "listen" to session changes?
 
Thanks for taking the time to read through.