Mouse wheel event to work with hovered control

前端 未结 4 1023
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 11:37

In my C# 3.5 Windows Forms application, I have a few SplitContainers. There is a list control inside each (dock fill). When the focus is on one of these controls and I move mous

4条回答
  •  攒了一身酷
    2021-02-04 12:07

    This is Brian Kennedy's answer completed with Hank Schultz comment:

    First you should make a class implements IMessageFilter:

    public class MessageFilter : IMessageFilter
    {
        private const int WM_MOUSEWHEEL = 0x020A;
        private const int WM_MOUSEHWHEEL = 0x020E;
    
        [DllImport("user32.dll")]
        static extern IntPtr WindowFromPoint(Point p);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
    
        public bool PreFilterMessage(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_MOUSEWHEEL:
                case WM_MOUSEHWHEEL:
                    IntPtr hControlUnderMouse = WindowFromPoint(new Point((int)m.LParam));
                    if (hControlUnderMouse == m.HWnd)
                    {
                        //Do nothing because it's already headed for the right control
                        return false;
                    }
                    else
                    {
                        //Send the scroll message to the control under the mouse
                        uint u = Convert.ToUInt32(m.Msg);   
                        SendMessage(hControlUnderMouse, u, m.WParam, m.LParam);
                        return true;
                    }
                default:
                    return false;
            }
        }
    }
    

    Example usage:

    public partial class MyForm : Form
    {
        MessageFilter mf = null;
    
        private void MyForm_Load(object sender, EventArgs e)
        {
            mf= new MessageFilter();
            Application.AddMessageFilter(mf);
        }
    
        private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.RemoveMessageFilter(mf);
        }
    }
    

提交回复
热议问题