Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get windows unlock event in c# windows application?

Tags:

c#

windows

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.

like image 710
Anish V Avatar asked Sep 06 '12 05:09

Anish V


1 Answers

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");
            }
        }
    }
}
like image 193
Lasse Christiansen Avatar answered Nov 07 '22 09:11

Lasse Christiansen