Normal handler for all right clicks

I would like to create one common handler for all right-clicks (or perhaps some other unique behavior, such as pressing the middle button, etc.) that occurs in my application. They will trigger the same action, for example. to activate the control that was clicked or display the help dialog box.

Is there a mechanism that allows me to intercept all click events in the application, each of which gives a link to the control that was clicked on? A brute force solution would be to use reflection to iterate over all the controls in all the forms I create and attach a handler to them, but I'm looking for something more complex.

+3
source share
1 answer

You can try to implement the IMessageFilter interface in your form. There are several other discussions and documentation on this. One of the possible solutions for you may look (create a form, place a button on it, add the necessary code below, run it and try right-clicking on the form and on the button):

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsApplication1
{
   public partial class Form1 : Form, IMessageFilter
   {
      private const int WM_RBUTTONUP = 0x0205;

      [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
      public static extern IntPtr GetCapture();

      public Form1()
      {
         InitializeComponent();
         Application.AddMessageFilter(this);
      }

      public bool PreFilterMessage(ref Message m)
      {
         if (m.Msg == WM_RBUTTONUP)
         {
            System.Diagnostics.Debug.WriteLine("pre wm_rbuttonup");

            // Get a handle to the control that has "captured the mouse".  This works
            // in my simple test.  You can read the documentation and do more research
            // on it if you'd like:
            // http://msdn.microsoft.com/en-us/library/ms646257(v=VS.85).aspx
            IntPtr ptr = GetCapture();
            System.Diagnostics.Debug.WriteLine(ptr.ToString());

            Control control = System.Windows.Forms.Control.FromChildHandle(ptr);
            System.Diagnostics.Debug.WriteLine(control.Name);

            // Return true if you want to stop the message from going any further.
            //return true;
         }

         return false;
      }
   }
}
+1
source

Source: https://habr.com/ru/post/1754699/


All Articles