平滑展开和折叠动画的WinForms

本文关键字:动画 WinForms 折叠 平滑 | 更新日期: 2023-09-27 17:52:50

我试图得到一个平滑的扩展和折叠动画为我的形式。我现在的动画很不稳定。这是动画的Gif。有没有另外一种不冻结表单的方法?

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();
            }
        }
    }

平滑展开和折叠动画的WinForms

创建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();
    }
};

并将代码改为:

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