Here's one way to accomplish what you want. I'm be interested if someone
comes up with a better one. Application.Idle being a static event makes
this task a little more complicated than it had to be.
Anyway, you should be able to cut/paste the code below directly into an
empty project in place of the default Form1.cs and it should run fine.
ShaneB
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace MyApp
{
public class Form1 : System.Windows.Forms.Form, IMessageFilter //
note that we're implementing IMessageFilter because we want the see all
messages coming in.
{
private System.Windows.Forms.Timer timer1;
private System.ComponentModel.IContainer components;
private static int iEnteredIdleTicks; // we need a static
variable since Application.Idle is a static event.
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new
System.Windows.Forms.Timer(this.components);
this.timer1.Enabled = true; // the timer will always
be running
this.timer1.Interval = 60000; // we'll check every 60
seconds to see if the application has been idle too long
this.timer1.Tick += new
System.EventHandler(this.timer1_Tick_1);
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.Name = "Form1";
}
[STAThread]
static void Main()
{
Application.Idle += new EventHandler(Application_Idle); //
we want to process Idle events
Application.Run(new Form1());
}
private static void Application_Idle(object sender, EventArgs e)
{
iEnteredIdleTicks = Environment.TickCount;
}
private void timer1_Tick_1(object sender, System.EventArgs e)
{
if ( (iEnteredIdleTicks != 0) && (Environment.TickCount -
iEnteredIdleTicks > 300000) )
// In the above line, my test timeout value is 300 seconds (5
minutes). Note that depending on when the timer event is fired, this
could effectively be as long as 5 minutes + the timer1.Interval.
{
timer1.Enabled = false; // Prevents any further timer
messages...just in case.
// <you would log off the user here>
Application.Exit();
}
}
public bool PreFilterMessage(ref Message m)
{
iEnteredIdleTicks = 0; // reset our ticks since we got a
new message to handle...ie, we're no longer idling.
return false;
}
}
}