How to detect if the mouse is inside the whole form and child controls?

前端 未结 4 1675
长发绾君心
长发绾君心 2020-12-06 02:23

I need to detect when the user moves the mouse over the Form and all its child controls and also when it leaves the Form. I tried the MouseEnter and Mouse

4条回答
  •  無奈伤痛
    2020-12-06 03:18

    You can hook the main message loop and preprocess/postprocess any (WM_MOUSEMOVE) message what you want.

    public class Form1 : Form {
        private MouseMoveMessageFilter mouseMessageFilter;
        protected override void OnLoad(EventArgs e) {
            base.OnLoad( e );
    
            this.mouseMessageFilter = new MouseMoveMessageFilter();
            this.mouseMessageFilter.TargetForm = this;
            Application.AddMessageFilter(this.mouseMessageFilter);
        }
    
        protected override void OnClosed(EventArgs e) {
            base.OnClosed(e);
            Application.RemoveMessageFilter(this.mouseMessageFilter);
        }
    
        private class MouseMoveMessageFilter : IMessageFilter {
            public Form TargetForm { get; set; }
    
            public bool PreFilterMessage( ref Message m ) {
                int numMsg = m.Msg;
                if ( numMsg == 0x0200 /*WM_MOUSEMOVE*/)
                    this.TargetForm.Text = string.Format($"X:{Control.MousePosition.X}, Y:{Control.MousePosition.Y}");
    
                return false;
            }
        }
    }
    

提交回复
热议问题