If you’re writing an application that displays sensitive data (i.e. must be very secure), or you’re working on an application run by multiple users sharing a windows login (yes, it still happens), you may want to implement a “Session Expiration” concept borrowed from the web world.  In other words, if a user has not been using the application (i.e. no mouse/keyboard activity) for X minutes, then require some kind of authentication (pin, employee id, login password, etc.)

 

How would you implement it?  WinForms fires Application.Idle event fires every time the application goes idle, i.e. when all messages in the application message queue have finished processing.  Note:  it does not fire again until the application has done something and then goes idle again.  So, in Application.Idle handler, start/restart a timer that will “wake up” your locking code (e.g. display a modal login form) in X minutes…    

 

Important:  Because Application.Idle is a static event, you must detach any event handlers attached to this event in the ApplicationExit event. If you do not detach these handlers, they will remain attached to the event and continue to consume memory.