当用户空闲或不活动使用静态类并调用静态方法时,我有一个关于在 Windows 窗体中设置计时器的问题。由于静态将在 exe 文件的生命周期内存在。我需要计时器来设置任何鼠标事件。如果用户有任何时间,那么我需要重置计时器。所以这是要求。这里是代码。
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace StaticApplicationTimeOut
{
public static class SetApplicationTimeOut
{
#region
/// <summary>
/// Private Timer Property
/// </summary>
private static Timer _timer;
/// <summary>
/// Timer Property
/// </summary>
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 static event EventHandler UserActivity;
#endregion
#region Constructor
#endregion
#region Inherited Methods
/// <summary>
///
/// </summary>
public static void SetTimeOut()
{
// postpone auto-logout by 30 minutes
_timer = new Timer
{
Interval = 500 // Timer set for 30 minutes
};
Application.Idle += Application_Idle;
_timer.Tick += new EventHandler(Timer_Tick);
}
/// <summary>
///
/// </summary>
public static void StopTimer()
{
// Stops the timer
_timer.Stop();
}
#endregion
#region Private Methods
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Application_Idle(object sender, EventArgs e)
{
_timer.Stop();
_timer.Start();
}
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO
{
public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));
[MarshalAs(UnmanagedType.U4)]
public UInt32 cbSize;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTime;
}
static uint GetLastInputTime()
{
uint idleTime = 0;
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
lastInputInfo.dwTime = 0;
uint envTicks = (uint)Environment.TickCount;
if (GetLastInputInfo(ref lastInputInfo))
{
uint lastInputTick = lastInputInfo.dwTime;
idleTime = envTicks - lastInputTick;
}
return ((idleTime > 0) ? (idleTime / 1000) : 0);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Timer_Tick(object sender, EventArgs e)
{
if (GetLastInputTime() > 180)
{
_timer.Stop();
Application.Idle -= Application_Idle;
MessageBox.Show("Application Terminating");
Application.Exit();
}
}
#endregion
}
}
就像如果我想停止我需要调用的计时器
SetApplicationTimeOut.StopTimer();
并用于启动计时器
SetApplicationTimeOut.SetTimeOut();
如果有任何时刻,它应该重置计时器。我怎样才能在静态类中实现这一点?