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 static Timer _timer;
-
-
-
- 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
-
- public SetApplicationTimeOut()
- {
- KeyPreview = true;
- FormClosed += ObservedForm_FormClosed;
- MouseMove += ObservedForm_MouseMove;
- KeyDown += ObservedForm_KeyDown;
- }
- #endregion
- #region Inherited Methods
- protected virtual void OnUserActivity(EventArgs e)
- {
-
- UserActivity?.Invoke(this, e);
- }
- public void SetTimeOut()
- {
-
- _timer = new Timer
- {
- Interval = (30 * 60 * 1000)
- };
- 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!