MouseEnter and MouseLeave events from a Panel and its child controls

后端 未结 9 807
我在风中等你
我在风中等你 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:41

    The mouse is "leaving" the panel as it enters the child control which is why it fires the event.

    You could add something along the following lines in the panel MouseLeave event handler:

    // Check if really leaving the panel
    if (Cursor.Position.X < Location.X ||
        Cursor.Position.Y < Location.Y ||
        Cursor.Position.X > Location.X + Width - 1 ||
        Cursor.Position.Y > Location.Y + Height - 1)
    {
        // Do the panel mouse leave code
    }
    
    0 讨论(0)
  • 2020-12-10 13:41

    This is a tricky one, and will be difficult to code reliably for. One idea is to "capture" the 3 incoming events in a list and execute your desired code once the list is complete (has the 3 desired events in the list). Then when you're done executing whatever code (or perhaps capture the combo of events in reverse), you could empty your list and have it ready for the next time that particular combo-event happens. Not ideal, but just a thought.

    Of course, that doesn't overcome the potential resolution issues & possible missed events Hans raised. Perhaps more context is in order.

    0 讨论(0)
  • 2020-12-10 13:43

    The solution is to track the number of enters/leaves. In you overall control add a counter:

    private int mouseEnterCount = 0;
    

    In the MouseEnter handler do this:

    if (++mouseEnterCount == 1)
    {
       // do whatever needs to be done when it first enters the control.
    }
    

    In the MouseLeave handler do this:

    if (--mouseEnterCount == 0)
    {
       // do whatever needs to be done when it finally leaves the control.
    }
    

    and do the above MouseEnter and MouseLeave event handlers for ALL the child controls as well as the containing object.

    0 讨论(0)
提交回复
热议问题