21

Would prefer an answer in C#, .Net 3.5 using WPF (Windows Forms also okay)

I have an application that is essentially a toolbar window or tray icon. It needs to detect if a user locks his/her workstation and walks away in order to update the person's status in a centralized system.

I can detect a session switch or a logout easily enough, using the SystemEvents, but I cannot for the life of me figure out how to detect or receive an event on Lock.

Thanks for any assistance.

Grady Werner
  • 459
  • 1
  • 3
  • 9
  • See http://stackoverflow.com/questions/44980/how-can-i-programmatically-determine-if-my-workstation-is-locked – Abhijit Mar 16 '09 at 23:51

3 Answers3

46

When you handle the Microsoft.Win32.SystemEvents.SessionSwitch event (which it sounds like you're already doing to detect logout), check to see if the Reason is SessionSwitchReason.SessionLock:

 using Microsoft.Win32;
 // ...
 // Somewhere in your startup, add your event handler:
    SystemEvents.SessionSwitch += 
       new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
 // ...

 void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
 {
     switch(e.Reason)
     {
         // ...
         case SessionSwitchReason.SessionLock:
            // Do whatever you need to do for a lock
            // ...
         break;
         case SessionSwitchReason.SessionUnlock:
            // Do whatever you need to do for an unlock
            // ...
         break;
         // ...
     }
 }
Binary Worrier
  • 50,774
  • 20
  • 136
  • 184
Daniel LeCheminant
  • 50,583
  • 16
  • 120
  • 115
2

You need to P/Invoke WTSRegisterSessionNotification.

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
BC.
  • 24,298
  • 12
  • 47
  • 62
1

Here is something from CodeProject.

http://www.codeproject.com/KB/vb/DetectWindowslockunlock.aspx

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445