UserControl: How to add MouseWheel Listener?

后端 未结 4 1534
既然无缘
既然无缘 2021-01-21 01:34

I\'m creating an UserControl that should react if the mouse is over the control and MouseWheel gets rotated.

Currently i\'m doing this as shown here:

            


        
4条回答
  •  -上瘾入骨i
    2021-01-21 02:37

    Copy pasted from http://social.msdn.microsoft.com/forums/en-US/winforms/thread/eb922ed2-1036-41ca-bd15-49daed7b637c/

    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    namespace WindowsApplication1 {
      public partial class Form1 : Form, IMessageFilter {
        public Form1() {
          InitializeComponent();
          Application.AddMessageFilter(this);
        }
    
        public bool PreFilterMessage(ref Message m) {
          if (m.Msg == 0x20a) {
            // WM_MOUSEWHEEL, find the control at screen position m.LParam
            Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
            IntPtr hWnd = WindowFromPoint(pos);
            if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null) {
              SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
              return true;
            }
          }
          return false;
        }
    
        // P/Invoke declarations
        [DllImport("user32.dll")]
        private static extern IntPtr WindowFromPoint(Point pt);
        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
      }
    }
    

    this works great, thx Hans Passant

提交回复
热议问题