Search code examples
c#windowswinformsanimationtimer

How do I stop an animation with a timer if the animated object came to a specific location?


I am trying to do some animations with panels and a timer in a C# Windows Forms project. Currently, there is a panel (in my code called 'pnSideBlock') which is located at the left edge of the window. Right next to it is a button.

The idea is that if the mouse enters the button, then the panel should relocate outside of the window (in my project the panel has a width of 20px, therefor I make its new location 20px outside of the window) and will move into it again with the help of a timer. As soon as the panel has reached a specific location, in my case 0px, then the timer should stop and the panel should stop moving.

But at the moment, the timer just keeps on going, which causes the panel to keep moving to the right.

    private void btnMainMenu_MouseEnter(object sender, EventArgs e)
    {
        pnSideBlock.Left = -20;

        timerForAnim.Enabled = true;

        if(pnSideBlock.Left == 0)
        {
            timerForAnim.Enabled = false;
        }

    }

    private void btnMainMenu_MouseLeave(object sender, EventArgs e)
    {
        timerForAnim.Enabled = false;
    }

    private void timerForAnim_Tick(object sender, EventArgs e)
    {
        pnSideBlock.Left += 1;
    }

Solution

  • according to your code you need to change it to be like this:

    private void btnMainMenu_MouseEnter(object sender, EventArgs e)
        {
            pnSideBlock.Left = -20;
    
            timerForAnim.Enabled = true;
        }
    
        private void btnMainMenu_MouseLeave(object sender, EventArgs e)
        {
            timerForAnim.Enabled = false;
        }
    
        private void timerForAnim_Tick(object sender, EventArgs e)
        {
            pnSideBlock.Left += 1;
            if(pnSideBlock.Left == 0)
            {
                timerForAnim.Enabled = false;
            }
        }
    

    this change is required becouse btnMainMenu_MouseEnter happen only once when you enter to the button with the mouse. and you need to check if the panel in place after every move.