C# 窗体渐变

C# Form gradual fade

我想做的就是以 100 的不透明度显示表单,然后在 X 时间后它开始淡化直到 0.0 的不透明度,我有算法但我不知道在哪里实现它,就像我在Form_Load 表单已经显示出最终的不透明度,以及在 InitializeComponent() 之后;

this.Opacity = 1.0;

for (float i = 1.0f; i >= 0.0f; i -= 0.1f)
{
    this.Opacity = i;
    Thread.Sleep(150);
}

使用 Shown Event, which happens only once after the Form loads, or, if you want it to happen every time the form gets Focus, use the Activated Event.

在Form1.cs中:

private void Form1_Shown(object sender, EventArgs e)
{
    this.Opacity = 1.0;

    for (float i = 1.0f; i >= 0.0f; i -= 0.1f)
    {
        this.Opacity = i;
        Thread.Sleep(150);
    }
}

在Form1.Designer.cs中:

this.Shown += new System.EventHandler(this.Form1_Shown);

如果要使窗体不可见但控件仍然可见,可以使用 TransparencyKey 属性:

private void Form1_Shown(object sender, EventArgs e)
{
    // Choose some obscure background that no other controls will have
    this.BackColor = Color.Red;
    this.TransparencyKey = this.BackColor;
}