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.
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
}
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
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With