Monday, November 7, 2011

Auto start/stop timer when keyboard& Mouse idle mode

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;


namespace afp_Login
{
public partial class Form2 : Form
{
int Timecounter = 0;
Stopwatch stopwarch;
TimeSpan ts;

public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
timer1.Start();
timer2.Start();
stopwarch = new Stopwatch();
stopwarch.Start();

}
private void timer1_Tick(object sender, EventArgs e)
{
ts = stopwarch.Elapsed;
string Elapsedtime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
lblTime.Text = Elapsedtime.ToString();

}

private void timer2_Tick(object sender, EventArgs e)
{
Timecounter++;
if (Timecounter > 30 && timer1.Enabled == true)
{
stopwarch.Stop();
timer1.Stop();
}
else if (Timecounter < 30 && timer1.Enabled == false)
{
stopwarch.Start();
timer1.Start();
}

}

private void Form2_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
Timecounter = 0;
}

private void Form2_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
Timecounter = 0;
}

}
}