Search code examples
c#mousehover

C# make panel visible for specific time after mouse move over other panel


I need to make panel visible for specific time after mouse move over other panel I have been solving this problem quite long. I tried to use Timer but I wasn't successful.

This is my code:

 this.MouseHover += new EventHandler(myMouseHover);

   [...]
   //event handler
   private void myMouseHover(object sender, EventArgs e)
        {

                this.prevPanel.Visible = true;
                this.nextPanel.Visible = true;

                /* here I want put timer */

                this.prevPanel.Visible = false;
                this.nextPanel.Visible = false;

        }

Solution

  • Depending on the type of timer you are using, you need to put the code that will hide your panel in response to the tick event.

    For example, using the System.Windows.Forms.Timer:

    System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
    
    // form constructor
    public myForm() 
    {
        myTimer.Interval = 1000;    // or whatever you need it to be
        myTimer.Tick += new EventHandler(TimerEventProcessor);   
    }
    
    private void myMouseHover(object sender, EventArgs e) 
    {
         this.prevPanel.Visible = true;
         this.nextPanel.Visible = true;
         myTimer.Start();
     }
    
    private void TimerEventProcessor(Object myObject, EventArgs myEventArgs) {
         myTimer.Stop();
         this.prevPanel.Visible = false;
         this.nextPanel.Visible = false;
    }
    

    There are other timers you could use, but the WinForms timer has the advantage of firing in the UI thread so you don't need to worry about it. One thing to note is that you need to think about what happens if the mouse hover event fires again before the timer expires.

    Finally, if you are using WPF instead of WinForms, you could probably do the whole thing in XAML using animation.