How to Check for Application Inactivity in .NET 2010

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.



Related Articles

Comments

  • Is this a DEAD THREAD?

    Posted by Blake McKenna on 08/25/2015 08:57am

    Just wondering if this thread is dead since I haven't received a response to my original question posted back on 6/17/2015?

    Reply
  • Software Developer

    Posted by Blake McKenna on 06/17/2015 01:53pm

    I can't get the PreFilterMessage Function to fire. I added the Implements IMessageFilter under my Form Class declaration. Also, this Form is the main form in my windows application and it is a MDI Container. Not sure if that matters or not. Anyway, I've set a breakpoint on the IF statement and it never gets hit...even when I click/move the mouse. Below is my code. Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Try If Timer1.Interval = SecondsTimeout Then 'SecondsTimeout is set to 5000 Timer1.Enabled = False gblnSessionTimedOut = True frmLogin.ShowDialog(Me) End If Catch ex As Exception EH.ErrorMessage = "frmMain/Timer1_Tick() - " & ex.Message & "~E" End Try EH.ProcessMessages(Me, sbr, EH.ErrorMessage) End Sub ' ' ' Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage Dim blnRetVal As Boolean = False Try 'Check for mouse movements and / or clicks Dim mouse As Boolean = (m.Msg = &H200; And m.Msg = &HA0; And m.Msg = &H100; And m.Msg) 'Check for keyboard button presses Dim kbd As Boolean = (m.Msg = &H100; And m.Msg

    Reply
  • Thx

    Posted by JoeLaFrite on 01/21/2015 02:46am

    Hi I'm not a user of this website. I found it with our friend google. Just want to thank you, i've been searching for a long time this kind of code. Very very usefull for me ! Thanks again, 3 years later :)

    Reply
  • Sr. developer

    Posted by Dennis Rehm on 11/28/2012 07:35am

    Thanks for this example. It got me started. However, I found that the VB.NET code did not work for me as written in VS2010. (As a note, the Timer has to be set up as enabled.) I added the following in the Form Load event: Application.AddMessageFilter(Me) I made the SecondsCount an instance variable instead of a static local variable. I also defined a second instance variable SecondsTimeout as Integer that contains the timeout value. I put a Textbox on the window that displays the seconds until the timeout is reached. All the code follows: Private SecondsTimeout As Integer = 10 Private SecondsCount As Integer = 0 Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage Dim mouse As Boolean = (m.Msg = &H200; And m.Msg = &HA0; And m.Msg = &H100; And m.Msg SecondsTimeout Then SecondsCount = 0 Timer1.Enabled = False MessageBox.Show("Program has been inactive for " + SecondsTimeout.ToString + " seconds.") Timer1.Enabled = True End If End Sub Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load Application.AddMessageFilter(Me) End Sub Thanks again for the sample.

    Reply
  • me

    Posted by Jim Parzych on 11/19/2012 07:38am

    Looks good and I will save for future use. Currently I need to check for overall computer inactivity and use the GetLastInputInfo api call: http://www.pinvoke.net/default.aspx/user32.getlastinputinfo

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: August 27, 2015 With the cloud enabling companies to spin up servers and stand up data stores more quickly, mobile apps can be created faster, reducing the time-to-value. But three major obstacles stand in the way for many organizations: The backlog of app project requests confronting every enterprise regardless of their internal app development capabilities Finding and employing better, faster tools to speed and simplify the process of developing those apps. The emergence of …

  • When individual departments procure cloud service for their own use, they usually don't consider the hazardous organization-wide implications. Read this paper to learn best practices for setting up an internal, IT-based cloud brokerage function that service the entire organization. Find out how this approach enables you to retain top-down visibility and control of network security and manage the impact of cloud traffic on your WAN.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date