Want to build the ChatGPT based Apps? Start here
Become a member
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
C# Corner Home
Technologies
Monthly Leaders
ASK A QUESTION
Forum guidelines
Sandeep Choudary
0
79
7.8k
How to set a timer in Windows application when user is idle
May 25 2020 6:30 PM
I have a question in Windows Forms on setting timer when the user is idle or Inactive. I need the timer to set even on any Mouse Events. If the user makes any moment then I need to reset the timer. So this is the requirement. Here goes the code.
using
System;
using
System.Windows.Forms;
using
Timer = System.Windows.Forms.Timer;
namespace
FormsTimerSetup.Globals
{
public
class
SetApplicationTimeOut : Form
{
#region
///
/// Private Timer Property
///
private
static
Timer _timer;
///
/// Timer Property
///
public
static
Timer Timer
{
get
{
return
_timer;
}
set
{
if
(_timer !=
null
)
{
_timer.Tick -= Timer_Tick;
}
_timer = value;
if
(_timer !=
null
)
{
_timer.Tick += Timer_Tick;
}
}
}
#endregion
#region Events
public
event
EventHandler UserActivity;
#endregion
#region Constructor
/// Default/Parameterless SetApplicationTimeOut Constructor
public
SetApplicationTimeOut()
{
KeyPreview =
true
;
FormClosed += ObservedForm_FormClosed;
MouseMove += ObservedForm_MouseMove;
KeyDown += ObservedForm_KeyDown;
}
#endregion
#region Inherited Methods
protected
virtual
void
OnUserActivity(EventArgs e)
{
// Invoking the UserActivity delegate
UserActivity?.Invoke(
this
, e);
}
public
void
SetTimeOut()
{
// postpone auto-logout by 30 minutes
_timer =
new
Timer
{
Interval = (30 * 60 * 1000)
// Timer set for 30 minutes
};
Application.Idle += Application_Idle;
_timer.Tick +=
new
EventHandler(Timer_Tick);
}
#endregion
#region Private Methods
private
void
ObservedForm_MouseMove(
object
sender, MouseEventArgs e)
{
OnUserActivity(e);
}
private
void
ObservedForm_KeyDown(
object
sender, KeyEventArgs e)
{
OnUserActivity(e);
}
private
void
ObservedForm_FormClosed(
object
sender, FormClosedEventArgs e)
{
FormClosed -= ObservedForm_FormClosed;
MouseMove -= ObservedForm_MouseMove;
KeyDown -= ObservedForm_KeyDown;
}
private
static
void
Application_Idle(
object
sender, EventArgs e)
{
_timer.Stop();
_timer.Start();
}
private
static
void
Timer_Tick(
object
sender, EventArgs e)
{
_timer.Stop();
Application.Idle -= Application_Idle;
MessageBox.Show(
"Application Terminating"
);
Application.Exit();
}
#endregion
}
}
I have implemented the code but unsure whether it is the right way of doing it.
Any leads would be appreciated. Thanks for going through the post and STAY SAFE!
Reply
Answers (
2
)
Ninject for winforms - how to apply ninject DI for MDI child
I need urgent help with Windows Forms