在实际项目中,我们经常需要弹出窗体来与用户交互,为了使弹出窗体不那么突兀,可以加些转换效果,淡入淡出就是其中一种。
using System; using System.Windows.Forms; namespace TestFormEffect { public partial class Form1 : Form { private readonly Timer _timer; private readonly double _inspeed; private readonly double _outspeed; private State _state; public const float Precision = 0.000001f; public Form1() { InitializeComponent(); _timer=new Timer(); _timer.Tick += timer1_Tick; _timer.Enabled = false; _inspeed = 20; _outspeed = 20; } private void Form1_Load(object sender, EventArgs e) { _state = State.In; _timer.Enabled = true; Opacity = 0; } private void timer1_Tick(object sender, EventArgs e) { switch (_state) { case State.In: Opacity += _inspeed/100; if (1 - Opacity <= Precision) { _timer.Enabled = false; } break; case State.Out: Opacity -= _outspeed/100; if (Opacity <= Precision) { this.Close(); _timer.Enabled = false; } break; } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; _state = State.Out; _timer.Enabled = true; } } enum State { In=1, Out } }