Posts tagged ‘Win32’

C#: How to Detect if a Workstation has been Locked and Unlocked

Here is a quick little console program which demonstrates how to detect if a computer has been either locked or unlocked using C#.  We simply subscribe to the SessionSwitchEventHandler Delegate for the lock or unlock reasons.

// using Microsoft.Win32;
public class CheckForWorkstationLocking : IDisposable
    private SessionSwitchEventHandler sseh;
    void SysEventsCheck( object sender, SessionSwitchEventArgs e )
        switch ( e.Reason )
            case SessionSwitchReason.SessionLock: Console.WriteLine( "Lock Encountered" ); break;
            case SessionSwitchReason.SessionUnlock: Console.WriteLine( "UnLock Encountered" ); break;

    public void Run()
        sseh = new SessionSwitchEventHandler( SysEventsCheck );
        SystemEvents.SessionSwitch += sseh;

    #region IDisposable Members

    public void Dispose()
        SystemEvents.SessionSwitch -= sseh;


Here is a the code in a console application code to run it:

CheckForWorkstationLocking workLock = new CheckForWorkstationLocking();


Console.WriteLine("Press ESC to exit...");
while ( true )
    ConsoleKeyInfo key = Console.ReadKey( true );
    if ( key.Key == ConsoleKey.Escape )