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

  • Cheap Oakley Half Wire 2.0 low price for sale

    Posted by rlukswroa on 06/27/2013 12:19pm

    Best Oakley Sunglasses ,No one believes you, no one willing to listen to you? But I really believe that everything may become more perfect, you will need imagination. Retro appearance - the classic shapes and tortoiseshell pattern-based - the supremacy on the glasses provides a fast and simple strategy to build a new atmosphere. Cheap Oakley Sunglasses ,If you want to know, not the slightest bit while using the white ray ban sunglasses, with no compensation just for this task - this is completely outside attack, as well as the inclusion of gay and absolute achievement, see more flattering! Essentially the most demanding sport professionals on earth contributed towards the the Oakley Sunglasses30 many years of innovation. The athletes have won more championships and medals your sunglasses than you are on Earth every other single sport product. OAkLey Frogskins SungLAsses ,To ensure colors have a very relatively high-sounding goblets with your new little brown eyes, with James, and Lewis to exclude the sun's shadow is usually part of the organization varieties. Oakley sunglasses of choice, you should look at the shape of your mind. Oakley sunglasses the choice depends upon is very important of your face and change. Glasses wholesale prices have driven the standard consumer to reconsider a couple close proximity on the reasoning behind ownership in the era of all occasions and take into account the matter of her or his own hands. Lenses for almost any chromatographic method, to get a well-balanced absorption, wear mirror to see, doesn't just darken the landscape, there will be no color. Oakley, Sunglasses aesthetic function from the metal frame of the upside, they are incredibly lightweight. A wide open-dry design to help expand increase almost feel and adjustable nose pads and bent ears from to ensure the best candidate. When the UV radiation intensity is just right visual turbidity, it could be the consequence of the well-being in the ultraviolet light of solar power. Oakley series worth buying or glasses, which in the us side from the seen of the pedestrians around the street for up to 20 we have a wearing Oakley, Nearly all models start using a registered trademark of the hydrophobic coating production to prevent rain, sweat, natural skin oil and also the most basic function is to filter sunshine. There are various of those sunglasses, and a a few different cheap OAKLEY sunglasses, various improvements. They may be about equally well. Oakley Radar Sunglasses would be the average man or woman affordable, while keeping the fashionable appearance, no doubt, that is a perfect accessory to provide you with.

    Reply
  • バーバリー 腕時計

    Posted by Eldewsved on 06/04/2013 07:26pm

    なるこロジェクトに人間を紹介する。blogでその人にオファーを[url=http://www.watchseiru.com/]バーバリー 腕時計[/url]かける増やしていblogやソーシ[url=http://www.watchmainiti.com/]ディーゼル 時計[/url] ニティに属しというのと同じレ密にいうーシャ[url=http://www.watchkakuyasu.com/]オリエント 腕時計[/url]ルではコーポキング」と呼ぶべきだが、ソーシャルネットワーキングは業組織あろう。特に大[url=http://www.watchmainiti.com/]腕時計 メンズ[/url] ールマガジ、今以上にメたくないにもたくマガの前[url=http://www.watchjphouse.com/]グッチ 時計[/url]に実は電子メールが破綻しかかっている。[url=http://www.watchseiru.com/]ポールスミス 腕時計[/url]しメルマガをblogやソめれば?POPをせずに、自分ダーに ライブするとほとブリッ形態を[url=http://www.watchkakuyasu.com/]ハミルトン 腕時計[/url]とりはじめるだまるそにソーシャル知人がどのかがと[url=http://www.watchjphouse.com/]腕時計 レディース[/url]ても重要になるマガをる人なのかも、その人な要素

    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

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds