Seems like I have been through this before. What I want to do is hide and show something, depending on whether the mouse is inside of a certain area. For instance, I have a container of some sort with lots of controls on it. When the mouse is anywhere inside of the container, I want a link to be visible. I can't simply use the MouseEnter/MouseLeave events on the container, because MouseLeave is triggered when the mouse enters a child control and the MouseEventArgs don't say anything about what control is being entered.
I tried several things that turned out to not be very reliable. The method that seems to have turned out reliably is a combination of MouseEnter and MouseLeave events on the container, on its parent container and on its child controls.
In the constructor, wire up the events. (My container wasn't parented at that point, so I had to add a separate check and wire it up on the first MouseEnter detection.) For the parent containers, both MouseEnter and MouseLeave are wired up as "leave" events, because entering the parent is the same as leaving "my" container.
// Set up events for detecting MouseEnter/Leave AddMouseEventsToChildren(this); this.MouseEnter += this_MouseEnter; this.MouseLeave += this_MouseLeave;
And here are the recursive methods to wire up children and parents.
private void AddMouseEventsToChildren(Control parent) { foreach (Control child in parent.Controls) { child.MouseLeave += this_MouseLeave; child.MouseEnter += this_MouseEnter; AddMouseEventsToChildren(child); } } private void AddMouseEventsToParents(Control child) { if (child.Parent != null) { // connect both enter and leave to MouseLeave() child.Parent.MouseEnter += this_MouseLeave; child.Parent.MouseLeave += this_MouseLeave; AddMouseEventsToParents(child.Parent); } }
Finally, here are the events:
Control _parent; void this_MouseEnter(object sender, EventArgs e) { // since we haven't been added to a control at creation... if (_parent == null) { _parent = this.Parent; AddMouseEventsToParents(this); } lnkShowActions1.Visible = true; lnkShowActions2.Visible = true; } void this_MouseLeave(object sender, EventArgs e) { var pos = this.PointToClient(Cursor.Position); if (!this.ClientRectangle.Contains(pos)) { lnkShowActions1.Visible = false; lnkShowActions2.Visible = false; } }