C# Show/hide element on MouseHover/MouseLeave of the parent
-
18-09-2019 - |
Question
In C#, we have the following:
- A
UserControl
containing aPictureBox
and an invisibleFlowPanel
.
What I want to achieve:
- When the
UserControl
is hovered (MouseHover
), the invisibleFlowPanel
will be set tovisible = true
. When the mouse leaves theUserControl
orFlowPanel
, theFlowPanel
should be setvisible = false
.
Using MouseLeave
on UserControl
doesn't do the job, because this event is triggered when the mouse enters FlowPanel
. Hiding the FlowPanel
when the mouse leaves FlowPanel
does it, but is buggy (sometimes MouseLeave
is triggered, sometimes not).
What's the best way to fix this?
Solution
i did somthing similar on one of my forms
do a if(contorl.Opacity = 1.0) inside your first event
private void Form1_MouseLeave(object sender, EventArgs e)
{
if (this.ClientRectangle.Contains(this.PointToClient(Cursor.Position)))
{
this.Opacity = 1.0;
}
else
{
int loopctr = 0;
for (loopctr = 100; loopctr >= 5; loopctr -= 10)
{
this.Opacity = loopctr / 99.0;
this.Refresh();
Thread.Sleep(100);
}
}
}
OTHER TIPS
In the case when FlowPanel.MouseLeave
isn't triggered, isn't UserControl.MouseLeave
triggered? I suppose that hiding on both events may do the trick.
This is a common UI problem. Mouse events come up as samples so it's possible that some pixel positions are missed and a control doesn't get the mouse up event.
A not so nice way that works is setting up some form of Timer when MouseHover is detected inside the Control and poll for the cursor in regular intervals (such as 342ms).