为WinForms制作动画

本文关键字:动画 WinForms | 更新日期: 2023-09-27 18:24:02

我有一个windows窗体。我希望,当点击某个按钮来设置窗体扩展的动画时,显示窗体的新部分(不必设置窗体,并设置其中一个窗体的动画)。

这可能吗?

为WinForms制作动画

依靠Timer可以获得足够好的效果。这里有一个示例代码,展示了如何在单击按钮后"动画化"主窗体不断增加的大小。通过增加/减少所有变量(X/Y股份有限公司值或间隔),您可以完全控制动画的"外观"。只需在表单和下面的代码中包含一个按钮(button1)和一个计时器(timer1)。

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int timerInterval, curWidth, curHeight, incWidth, incHeight, maxWidth, maxHeight;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            curWidth = this.Location.X + this.Width;
            curHeight = this.Location.Y + this.Height;
            incWidth = 100;
            incHeight = 20;
            maxWidth = 2000;
            maxHeight = 1500;
            timerInterval = 100;
            timer1.Enabled = false;
            timer1.Interval = timerInterval;
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            curWidth = curWidth + incWidth;
            curHeight = curHeight + incHeight;
            if (curWidth >= maxWidth)
            {
                curWidth = maxWidth;
            }
            if (curHeight >= maxHeight)
            {
                curHeight = maxHeight;
            }
            this.Width = curWidth;
            this.Height = curHeight;
            if (this.Width == maxWidth && this.Height == maxHeight)
            {
                timer1.Stop();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
              timer1.Enabled = !timer1.Enabled;
        }
    }
}