Search code examples
c#visiblemouseleavemousehover

C# Show/hide element on MouseHover/MouseLeave of the parent


In C#, we have the following:

  • A UserControl containing a PictureBox and an invisible FlowPanel.

What I want to achieve:

  • When the UserControl is hovered (MouseHover), the invisible FlowPanel will be set to visible = true. When the mouse leaves the UserControl or FlowPanel, the FlowPanel should be set visible = 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);
          }
       }
    }