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!
amir ansariPosted Jan 19, 2022, 5:36 AM
where is implement in which page and place or create new cs file. please quick reply i waiting for this. please show step by step implementation
Amit GuptaPosted May 26, 2020, 12:21 AM