Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a workstation lock

I'm developing an application and I'm trying to detect when the workstation gets locked, for example by the user pressing the Windows + L keys.

I know that the lock event has the value

  WTS_SESSION_LOCK 0x7

But i don't know how to use it. I've searched the web but found nothing.

like image 745
Newbie Avatar asked Jul 25 '13 01:07

Newbie


2 Answers

You should use the SystemEvents class in the Microsoft.Win32 namespace, especially the SystemEvents.SessionSwitch event.

SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;  // Subscribe to the SessionSwitch event

static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
    if (e.Reason == SessionSwitchReason.SessionLock)
        // Add your session lock "handling" code here
}

Update

If you need to have this event activated from the program startup in a Winforms application:

static class Program
{
    [STAThread]
    private static void Main()
    {
        SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;  // Subscribe to the SessionSwitch event

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
    {
        if (e.Reason == SessionSwitchReason.SessionLock)
            // Add your session lock "handling" code here
    }
}
like image 67
Cédric Bignon Avatar answered Oct 03 '22 00:10

Cédric Bignon


Finnallly managed to do it on VB :D

First you need to import the libs:

Imports System
Imports Microsoft.Win32
Imports System.Windows.Forms

Then you add the handler:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    AddHandler SystemEvents.SessionSwitch, AddressOf SessionSwitch_Event

End Sub

Finnally you create the sub that captures it:

Private Sub SessionSwitch_Event(ByVal sender As Object, ByVal e As SessionSwitchEventArgs)

    If e.Reason = SessionSwitchReason.SessionLock Then
        MsgBox("Locked")
    End If
    If e.Reason = SessionSwitchReason.SessionUnlock Then
        MsgBox("Unlocked")
    End If
End Sub

Last you remove the handler:

Private Sub closing_event(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    RemoveHandler SystemEvents.SessionSwitch, AddressOf SessionSwitch_Event
End Sub
like image 39
Newbie Avatar answered Oct 03 '22 02:10

Newbie