Handling all mouse movements at the Main Form level in C#

In a C# WinForms application, mouse movement events always go to the child control that the mouse moves over. Sometimes you might want to track mouse movements at the Form level instead of handling them at the child control level. To do this you need to handle the raw windows messages at the application level. Here’s the source code for doing this:

      public partial class MainForm : Form

      {

            [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]

            public class TestMessageFilter : IMessageFilter

            {

                  const int WM_MOUSEMOVE = 0x200;

                  static int count = 0;

                  public bool PreFilterMessage(ref Message m)

                  {

                        // Blocks all the messages relating to the left mouse button.

                        if (m.Msg == WM_MOUSEMOVE)

                        {

                              System.Diagnostics.Trace.WriteLine("Mouse Moved " + (++count).ToString());

                              return true;

                        }

                        return false;

                  }

            }

 

            public MainForm()

            {

                  InitializeComponent();

                  Application.AddMessageFilter(new TestMessageFilter());

            }

 

The WM_MOUSEMOVE constant is from C/C++ programming and is part of the Win32 API. It’s declared in Winuser.h which can be found in the Windows SDK if you have Visual C++ installed.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment