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;
    }

    #endregion
}

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

CheckForWorkstationLocking workLock = new CheckForWorkstationLocking();

workLock.Run();

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