C#把子控件的MouseUP MouseDown MouseMove三个事件提交到父控件

相当于 this.KeyPreview = true;的效果只是我之添加了几个事件而已.

 

很简单使用HOOK 获取消息 计算坐标返回到指定控件上

 

使用方法


        private MousePreview m_MousePreview;

    
        private void Form1_Load(object sender, EventArgs e)
        {
          
            m_MousePreview = new MousePreview(panel1);

                     
        }

 

 

下面是全部的类

 

  /// <summary> /// 把鼠标 DOWN UP MOVE 三个事件提交到父窗体上 /// [email protected] /// </summary> public class MousePreview { [DllImport("kernel32")] public static extern int GetCurrentThreadId(); [DllImport("user32", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetWindowsHookEx(int idHook, HOOKPROC lpfn, int hmod, int dwThreadId); [DllImport("user32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); public delegate int HOOKPROC(int nCode, int wParam, int lParam); private Control m_Control; public MousePreview(Control p_Control) { SetWindowsHookEx(7, new HOOKPROC(MyMouseProc), 0, GetCurrentThreadId()); m_Control = p_Control; } public int MyMouseProc(int nCode, int wParam, int lParam) { if (nCode == 0) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Rectangle _Rect = m_Control.RectangleToScreen(m_Control.ClientRectangle); if (!_Rect.Contains(Cursor.Position)) return 0; short _X = (short)(Cursor.Position.X - _Rect.X); short _Y = (short)(Cursor.Position.Y - _Rect.Y); int _Point = _Y << 16; _Point += _X; switch (wParam) { case 512: SendMessage(m_Control.Handle, 512, wParam, _Point); break; case 513: SendMessage(m_Control.Handle, 513, wParam, _Point); break; case 514: SendMessage(m_Control.Handle, 514, wParam, _Point); break; case 516: SendMessage(m_Control.Handle, 516, wParam, _Point); break; case 517: SendMessage(m_Control.Handle, 517, wParam, _Point); break; default: break; } } return 0; } }

 

你可能感兴趣的:(object,C#,user,Class,UP,hook)