How to Check for Application Inactivity in .NET 2010

Friday Nov 16th 2012 by Hannes Du Preez
Share:

Hannes du Preez shows you how to build an inactivity feature into your VB.NET and C# applications to allow them to check for inactivity.

Introduction

A nice feature to build into your application is allowing your application to check for inactivity. Inactivity means that the program is just "standing still" - it is open, but it seems to be forgotten. Some programs check for inactivity in order to release important resources. Some programs rely on activity in order to keep database connections open, etc. In this article we will let our program check for inactivity.

Logic

There are actually a few ways to accomplish this: You could use a normal timer and check for mouse movements, clicks, or keyboard presses. You could determine this through scanning the active processes running on your computer. The question is: How complicated do you want to get?

My method involves the IMessageFilter Interface. This interface allows an application to capture a message before it is dispatched to a control or form. Yes, it may also be more complicated than just checking the mouse movements and key presses one-by-one, but it is a lot less code and actually accomplishes the same thing. By using this method, you are 100% sure that there will not be any glitches or miscalculations.

The IMessageFilter also checks mouse movements and key presses, but it does so through the use of the actual mouse messages and key messages being sent. Sound complicated? No, don't worry - as you'll see shortly, it is quite a breeze.

Design

Start up Visual Studio and choose either VB.NET or C#. Create a Windows Forms Project. There will be some differences in our VB and C# projects, because C# will implement this Interface differently than VB. Add a few controls to your form, and add a Timer (which is the most important here). For the Timer, set the Interval Property to 1000 (One second).

VB.NET Code

As to be expected, there is not much code involved here, but that doesn't mean that the code won't have us scratch our heads :). For simplicity's sake, let us cover VB.NET and C# separately.

Open the code window for your VB.NET project, and add the following code :

Public Class Form1
Implements IMessageFilter 'This interface allows an application to capture a message before it is dispatched to a control or form.

Here, we are letting our form know that we will be using IMessageFilter messages. Now we need to write the Function responsible for listening to the sent messages:

 '' Filters out a message before it is dispatched.
Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage

'Check for mouse movements and / or clicks
Dim mouse As Boolean = (m.Msg >= &H200 And m.Msg <= &H20D) Or (m.Msg >= &HA0 And m.Msg <= &HAD)

'Check for keyboard button presses
Dim kbd As Boolean = (m.Msg >= &H100 And m.Msg <= &H109)

If mouse Or kbd Then 'if any of these events occur
If Not Timer1.Enabled Then MessageBox.Show("Waking up") 'wake up
Timer1.Enabled = False
Timer1.Enabled = True

Return True

Else
Return False
End If
End Function

This function identifies each message sent to the form. These messages can be mouse clicks, mouse movements, key presses, etc. We wait for a message, then the program wakes up.

The final piece of code we need to add is the Timer's Tick event. This will serve to wait for messages. If messages haven't been received in two minutes, we quit. Add this code now:

 Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

Static SecondsCount As Integer 'Counts each second
SecondsCount += 1 'Increment

If SecondsCount > 120 Then 'Two minutes have passed since being active
Timer1.Enabled = False
MessageBox.Show("Program has been inactive for 2 minutes…. Exiting Now…. Cheers!")
Application.Exit()
End If
End Sub

When our counter variable reaches 120 ( 2 minutes ) the program quits.

C# Code

Apart from the syntactical changes between VB.NET and C#, there are some other differences too. In C#, we cannot Implement the IMessageFilter Interface the same way we did in VB.NET. We have to create a separate class, and then make use of that class from within our form. In your C# Project, add a Class named FilterMess and add the following code to it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms; //Necessary

namespace Inactivity_C //Name of my program
{
class FilterMess : IMessageFilter //This interface allows an application to capture a message before it is dispatched to a control or form
{
private Form1 FParent; //instance of the form in which you want to handle this pre-processing

public FilterMess(Form1 RefParent)
{
FParent = RefParent;
}

public bool PreFilterMessage(ref Message m)
{
bool ret = true;

//Check for mouse movements and / or clicks
bool mouse = (m.Msg >= 0x200 & m.Msg <= 0x20d) | (m.Msg >= 0xa0 & m.Msg <= 0xad);

//Check for keyboard button presses
bool kbd = (m.Msg >= 0x100 & m.Msg <= 0x109);

//if any of these events occur
if (mouse | kbd)
{
MessageBox.Show("Waking up");
//wake up
ret = true;
}
else
{
ret = false;
}

return ret;

}

}
}

It is more or less the same as in VB.NET. I just added the ability to connect this class to my Form (named Form1). All we need to do now is to make use of this class inside our form. Change your Form's constructor as follows:

 public Form1()
{
InitializeComponent();
Application.AddMessageFilter(new FilterMess(this)); //Connect to FilterMess class
}

Finally, add your Timer_Tick event:

 static int SecondsCount;
private void timer1_Tick(object sender, EventArgs e)
{

//Counts each second
SecondsCount += 1;
//Increment

//Two minutes have passed since being active
if (SecondsCount > 120) {
timer1.Enabled = false;
MessageBox.Show("Program has been inactive for 2 minutes…. Exiting Now…. Cheers!");
Application.Exit();
}
}

When run and left inactive for two minutes, a messagebox will pop up informing you that your application has been inactive for too long, and exits. If your application (form) didn't become inactive, you'd get a message each time you did something. That can get a tad annoying, but this is obviously just an example (which you will be able to download) for you to use as you wish.

Conclusion

Not too complicated now was it? Nope. I hope you have enjoyed this article and that you can benefit from it. Until next time, cheers!

About the Author:

Hannes du Preez is a Microsoft MVP for Visual Basic for the fifth year in a row. He is a trainer at a South African-based company providing IT training in the Vaal Triangle. You could reach him at hannes [at] ncc-cla [dot] com.

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved