Find how much time application idle in windows application
public partial class Form1 : Form,IMessageFilter
{
Timer timer;
private DateTime _wentIdle;
private int _idleTicks;
public Form1()
{
InitializeComponent();
Application.AddMessageFilter(this);
timer = new Timer();
timer.Interval = 1000;
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
TimeSpan diff = DateTime.Now - _wentIdle;
if (diff.TotalSeconds >= Settings.Default.IdleTimeout_Sec)
{
label1.Text = "Idle From - " + _wentIdle;
}
if (++_idleTicks >= Settings.Default.IdleTimeout_Sec)
{
label1.Text = "Idle From - " + _idleTicks;
}
if (_idleTicks > 100)
{ Application.Exit(); }
}
private void Form1_Load(object sender, EventArgs e)
{
Application.Idle += Application_Idle;
}
void Application_Idle(object sender, EventArgs e)
{
_wentIdle = DateTime.Now;
}
public bool PreFilterMessage(ref Message m)
{
if (isUserInput(m))
{
_wentIdle = DateTime.MaxValue;
_idleTicks = 0;
label1.Text = "We Are NOT idle!";
}
return false;
}
private bool isUserInput(Message m)
{
if (m.Msg == 0x200) { return true; }
if (m.Msg == 0x020A) { return true; }
if (m.Msg == 0x100) { return true; }
if (m.Msg == 0x101) { return true; }
return false;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
}
No comments:
Post a Comment