Blog Stats
  • Posts - 1
  • Articles - 0
  • Comments - 4
  • Trackbacks - 2

 

Thursday, February 02, 2006

Using IMessageFilter class in C#


I was rather curious to find out how to use the IMessageFilter class in .NET. But one day I had to go this way to achieve a set of functionality in my project.

The objective was to capture any event which flows to your application before it reaches any control on the application and do certain things. In my case, at the hit of “CTRL+ALT+Y”, I wanted to invoke certain form. In a normal form, you can write this in one of the normal KEY events of the form. But when you hv a USER -CONTROL with layers of inheritence and lot of controls over it then KEY events doesn't get traslated  and they never get fired.

So the only possible solution was to capture the strokes as they they flow from the key-board towards the intended application. I think it was a very powerful technique. So its time to look at some of the code. There are 2 approaches you can do this:

A. a)Have a separate class  which derives from the IMessageFilterInterface. You need to implement the PreFilterMessage of this interface.

public class TestMessageFilter : IMessageFilter
 {
  private Form1 FOwner; //instance of the form in which you want to handle this pre-processing
  const int WM_KEYUP         = 0x101;
  public TestMessageFilter(Form1 aOwner)
  {
   FOwner = aOwner;
  }

  public bool PreFilterMessage(ref Message m)
  {
    bool ret = true;
   if (m.Msg == WM_KEYUP)
   {         
      Keys key = (Keys)(int)m.WParam & Keys.KeyCode;
  if(key = =  Keys.Y)
 {
    if((int)Control.ModifierKeys == ((int)Keys.Control + (int)Keys.Alt))
     {
                //got it......
     }
     else
            { ret = false;
             } 
       
        }   
          
             return ret;
   }
   else
   {
    return false;
   }
  }
 }
 }

b) After the separate class, we need to attach this pre-filtering to the current class/form, so in the constructor of the Form, write this :

Application.AddMessageFilter(new TestMessageFilter(this));

See the every-message beiing caught which flows from your mouse/keyboard in your application.

That's it your are done:

B. Second approach :  Have the current Form/Class directly implement this function :

 i.e Form1 : System.Windows.Forms.Form, IMessageFilter.{...}

and now put the above PreFilterMessage function directly inside the Form. One last thing you will have to do here is this: in the constructor of the form now, we need to make a little modification the way we attach the message filter i.e Application.AddMessageFilter(this);

//notice the use of “this” directly here, unlike above where we had to pass the object of the TestMessageFilter class.

Enjoy!!!!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
 

 

Copyright © Mehnaz Singh