Edit: Adam is absolutely right, I've misunderstood the question, so I deleted my original answer.
To monitor user activity, you could create a custom Form-based class from which your application forms will inherit. There you can subscribe to the MouseMove and KeyDown events (setting the KeyPreview property to true), either of which will be raised whenever the user is active. You can then create a System.Threading.Timer, with the due time set to 30 minutes, and postpone it using the Change() method whenever user activity is detected.
This is an example implementation below: the ObservedForm is written to be rather general, so that you can more easily see the pattern.
public class ObservedForm : Form
{
public event EventHandler UserActivity;
public ObservedForm()
{
KeyPreview = true;
FormClosed += ObservedForm_FormClosed;
MouseMove += ObservedForm_MouseMove;
KeyDown += ObservedForm_KeyDown;
}
protected virtual void OnUserActivity(EventArgs e)
{
var ua = UserActivity;
if(ua != null)
{
ua(this, e);
}
}
private void ObservedForm_MouseMove(object sender, MouseEventArgs e)
{
OnUserActivity();
}
private void ObservedForm_KeyDown(object sender, KeyEventArgs e)
{
OnUserActivity();
}
private void ObservedForm_FormClosed(object sender, FormClosedEventArgs e)
{
FormClosed -= ObservedForm_FormClosed;
MouseMove -= ObservedForm_MouseMove;
KeyDown -= ObservedForm_KeyDown;
}
}
Now you can subscribe to the UserActivity event, and do the logics you desire, for example:
private System.Threading.Timer timer = new Timer(_TimerTick, null, 1000 * 30 * 60, Timeout.Infinite);
private void _OnUserActivity(object sender, EventArgs e)
{
if(timer != null)
{
// postpone auto-logout by 30 minutes
timer.Change(1000 * 30 * 60, Timeout.Infinite);
}
}
private void _TimerTick(object state)
{
// the user has been inactive for 30 minutes; log him out
}
Hope this helps.
Edit #2: rephrased some parts of the explanation for clarity, and changed the use of the FormClosing event to FormClosed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…