How to Check for Application Inactivity in .NET 2010


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.


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.


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).


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

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!")
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;
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()
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;

//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!");

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.


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


  • 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

  • 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 :)

  • 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.

  • バーバリー 腕時計

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

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

  • 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.

  • 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:

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

Top White Papers and Webcasts

  • U.S. companies are desperately trying to recruit and hire skilled software engineers and developers, but there is simply not enough quality talent to go around. Tiempo Development is a nearshore software development company. Our headquarters are in AZ, but we are a pioneer and leader in outsourcing to Mexico, based on our three software development centers there. We have a proven process and we are experts at providing our customers with powerful solutions. We transform ideas into reality.

  • 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