How to Check for Application Inactivity in .NET 2010

December 4, 2012 § Leave a comment

Posted by Hannes Du Preez

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

  1. Public Class Form1
  2. 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:

  1. ” Filters out a message before it is dispatched.
  2. Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
  3. ‘Check for mouse movements and / or clicks
  4. Dim mouse As Boolean = (m.Msg >= &H200 And m.Msg <= &H20D) Or (m.Msg >= &HA0 And m.Msg <= &HAD)
  5. ‘Check for keyboard button presses
  6. Dim kbd As Boolean = (m.Msg >= &H100 And m.Msg <= &H109)
  7. If mouse Or kbd Then ‘if any of these events occur
  8. If Not Timer1.Enabled Then MessageBox.Show(“Waking up”) ‘wake up
  9. Timer1.Enabled = False
  10. Timer1.Enabled = True
  11. Return True
  12. Else
  13. Return False
  14. End If
  15. 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:

  1. Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
  2. Static SecondsCount As Integer ‘Counts each second
  3. SecondsCount += 1 ‘Increment
  4. If SecondsCount > 120 Then ‘Two minutes have passed since being active
  5. Timer1.Enabled = False
  6. MessageBox.Show(“Program has been inactive for 2 minutes…. Exiting Now…. Cheers!”)
  7. Application.Exit()
  8. End If
  9. 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 namedFilterMess and add the following code to it:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows.Forms; //Necessary
  6. namespace Inactivity_C //Name of my program
  7. {
  8. class FilterMess : IMessageFilter //This interface allows an application to capture a message before it is dispatched to a control or form
  9. {
  10. private Form1 FParent; //instance of the form in which you want to handle this pre-processing
  11. public FilterMess(Form1 RefParent)
  12. {
  13. FParent = RefParent;
  14. }
  15. public bool PreFilterMessage(ref Message m)
  16. {
  17. bool ret = true;
  18. //Check for mouse movements and / or clicks
  19. bool mouse = (m.Msg >= 0x200 & m.Msg <= 0x20d) | (m.Msg >= 0xa0 & m.Msg <= 0xad);
  20. //Check for keyboard button presses
  21. bool kbd = (m.Msg >= 0x100 & m.Msg <= 0x109);
  22. //if any of these events occur
  23. if (mouse | kbd)
  24. {
  25. MessageBox.Show(“Waking up”);
  26. //wake up
  27. ret = true;
  28. }
  29. else
  30. {
  31. ret = false;
  32. }
  33. return ret;
  34. }
  35. }
  36. }

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

  1. public Form1()
  2. {
  3. InitializeComponent();
  4. Application.AddMessageFilter(new FilterMess(this)); //Connect to FilterMess class
  5. }

Finally, add your Timer_Tick event:

  1. static int SecondsCount;
  2. private void timer1_Tick(object sender, EventArgs e)
  3. {
  4. //Counts each second
  5. SecondsCount += 1;
  6. //Increment
  7. //Two minutes have passed since being active
  8. if (SecondsCount > 120) {
  9. timer1.Enabled = false;
  10. MessageBox.Show(“Program has been inactive for 2 minutes…. Exiting Now…. Cheers!”);
  11. Application.Exit();
  12. }
  13. }

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.

Where Am I?

You are currently viewing the archives for December, 2012 at Naik Vinay.