Introduction
Days ago, I was trying to implement a new functionality to lock user sessions in WinForm applications when a session has not been used by X minutes. That functionality is common in many software but I found few articles about this topic. For this reason, I decided to write this small article to share my experience using the Application.Idle event.
Background
The Idle
event is invoked when the application finishes processing and is about to enter the idle state. How to know idle time of the application? This is the goal of this code.
Using the Code
In this code, I going to show, for me, the most simple way to resolve this question.
First step: Subscribe to the idle event:
public IdleSampleForm()
{
InitializeComponent();
Application.Idle += Application_Idle;
Application.ApplicationExit += Application_ApplicationExit;
}
...........................
private void Application_ApplicationExit(object sender, EventArgs e)
{
Application.Idle -= Application_Idle;
}
Second step: Create timer as trigger to check the inactive elapsed time:
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
...........................
private void timer1_Tick(object sender, EventArgs e)
{
_ignore_action = true;
}
Third step: Implement idle event:
private void Application_Idle(object sender, EventArgs e)
{
if (LoginController.getInstance().OnlineUser != null && !_lockActive)
{
DateTime _now = DateTime.Now;
TimeSpan _timeSpan = _now - _last_time_idle;
..........................
if (_timeSpan.TotalMinutes > LoginController.TimeForIdleMin)
{
_lockActive = true;
.......................................
if (!_ignore_action)
{
_last_time_idle = DateTime.Now;
}
}
_ignore_action = false;
}
Points of Interest
The timer always generates an invocation of idle event. For this reason, it is very important to use _ignore_action
variable or another form to avoid set _last_time_idle
by this invocation.
History
- April 20th, 2016: Created