MouseEnter and MouseLeave events from a Panel and its child controls

后端 未结 9 827
我在风中等你
我在风中等你 2020-12-10 13:14

I have a Panel that contains child controls.

If I handle the Panel\'s MouseEnter and MouseLeave events, and its c

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 13:25

    Jimmy T. is right. There will be problems if there is no (or small) space betwean Parent Control (Panel) edge and Child Control.

    This is how I solve this problem in UserControl-derived class:

        public CSStackPanelItem()
        {
            InitializeComponent();
    
            MouseEnter += new EventHandler(CSStackPanelItem_MouseEnter);
    
            foreach (Control child in Controls)
            {
                child.MouseEnter += (s, e) => CSStackPanelItem_MouseEnter(s, e);
                child.MouseLeave += (s, e) => OnMouseLeave(e);
            }
        }
    
        protected override void OnMouseLeave(EventArgs e)
        {
            if (this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)))
                return; //suppress mouse leave event handling
    
            if (m_bIsHover)
            {
                m_bIsHover = false;
                Invalidate(); //actually my mouse Enter/Leave event
            }
    
            base.OnMouseLeave(e);
        }
    
        void CSStackPanelItem_MouseEnter(object sender, EventArgs e)
        {
            m_bIsHover = true;
            Invalidate(); //actually my mouse Enter/Leave event
        }
    

提交回复
热议问题