0

Im trying to get a smooth expanding and collapsing animation for my form. My current animation is really jittery and non consistent. Heres a Gif of the Animation. Is there another way to do this that doesnt freeze the form?

private void ShowHideToggle_CheckStateChanged(object sender, EventArgs e)
    {
        if (ShowHideToggle.Checked) //checked = expand form
        {
            ShowHideToggle.Text = "<";
            while (Width < originalWidth)
            {
                Width++;
                Application.DoEvents();
            }
        }
        else
        {
            ShowHideToggle.Text = ">";
            while(Width > 24)
            {
                Width--;
                Application.DoEvents();
            }
        }
    }
Snazzie
  • 197
  • 1
  • 3
  • 12
  • 2
    As an added note, you should avoid `DoEvents`...[it's really bad](http://stackoverflow.com/questions/5181777/use-of-application-doevents). – DonBoitnott Jun 28 '16 at 10:55
  • _Smooth .. Animation_ and _WinForms_ do not go together well, I'm sorry to say.. – TaW Jun 28 '16 at 11:10

1 Answers1

2

Create a Timer:

Timer t = new Timer();
t.Interval = 14;
t.Tick += delegate
{
    if (ShowHideToggle.Checked)
    {
        if (this.Width > 30) // Set Form.MinimumSize to this otherwise the Timer will keep going, so it will permanently try to decrease the size.
            this.Width -= 10;
        else
            t.Stop();
    }
    else
    {
        if (this.Width < 300)
            this.Width += 10;
        else
            t.Stop();
    }
};

And change your code to:

private void ShowHideToggle_CheckStateChanged(object sender, EventArgs e)
{
    t.Start();
}