10

I want to track the windows unlock event in a windows application. How is it done? What is the event used for that? Does I need to import any namespace for that?

While a user unlocks the windows, the application needs to do some tasks.

Anish V
  • 673
  • 3
  • 17
  • 38
  • Possible duplicate of: http://stackoverflow.com/questions/603484/checking-for-workstation-lock-unlock-change-with-c-sharp or this http://stackoverflow.com/questions/44980/how-can-i-programmatically-determine-if-my-workstation-is-locked – Lasse Christiansen Sep 06 '12 at 05:12
  • The answers in that link was not up to the mark. :( – Anish V Sep 06 '12 at 05:14
  • I added one more link - there seems to be many "instances" of this type of question at StackOverflow. However, I posted one of them as my answer as it included sample code you might find useful. – Lasse Christiansen Sep 06 '12 at 05:17

1 Answers1

28

As posted in this StackOverflow answer: https://stackoverflow.com/a/604042/700926 you should take a look at the SystemEvents.SessionSwitch Event.

Sample code can be found in the referred answer as well.

I just took the code shown in the referred StackOverflow answer for a spin and it seems to work on Windows 8 RTM with .NET framework 4.5.

For your reference, I have included the complete sample code of the console application I just assembled.

using System;
using Microsoft.Win32;

// Based on: https://stackoverflow.com/a/604042/700926
namespace WinLockMonitor
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
            Console.ReadLine();
        }

        static void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
        {
            if (e.Reason == SessionSwitchReason.SessionLock)
            {
                //I left my desk
                Console.WriteLine("I left my desk");
            }
            else if (e.Reason == SessionSwitchReason.SessionUnlock)
            {
                //I returned to my desk
                Console.WriteLine("I returned to my desk");
            }
        }
    }
}
Community
  • 1
  • 1
Lasse Christiansen
  • 10,205
  • 7
  • 50
  • 79
  • I'm using a windows application. Where do I need to add the `Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);` – Anish V Sep 06 '12 at 05:52
  • This one worked fine. I have added the above code inside the form's initialize event. – Anish V Sep 06 '12 at 06:07