Capturing mouse events from every component

前端 未结 4 1237
醉酒成梦
醉酒成梦 2020-11-28 06:56

I have a problem with MouseEvents on my WinForm C# application.

I want to get all mouse clicks on my application, but I don\'t want to put a listener in eve

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 07:55

    If you don't want to handle the messages by overriding Form.PreProcessMessage or Form.WndProc then you could subclass Form to hook an event handler to all the MouseClick events from the various controls on the form.
    EDIT: forgot to recurse through child controls of controls on the form.

        public class MousePreviewForm : Form
        {
          protected override void OnClosed(EventArgs e)
          {
             UnhookControl(this as Control);
             base.OnClosed(e);
          }
    
          protected override void OnLoad(EventArgs e)
          {
             base.OnLoad(e);
    
             HookControl(this as Control);
          }
    
          private void HookControl(Control controlToHook)
          {
             controlToHook.MouseClick += AllControlsMouseClick;
             foreach (Control ctl in controlToHook.Controls)
             {
                HookControl(ctl);
             }      
          }
    
          private void UnhookControl(Control controlToUnhook)
          {
             controlToUnhook.MouseClick -= AllControlsMouseClick;
             foreach (Control ctl in controlToUnhook.Controls)
             {
                UnhookControl(ctl);
             }
          }
    
          void AllControlsMouseClick(object sender, MouseEventArgs e)
          {
             //do clever stuff here...
             throw new NotImplementedException();
          }
       }
    

    Your forms would then need to derive from MousePreviewForm not System.Windows.Forms.Form.

提交回复
热议问题