C#形式逐渐淡出

时间:2017-04-22 00:36:52

标签: c# winforms opacity

我想要做的就是显示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);
}

1 个答案:

答案 0 :(得分:1)

使用Shown Event,只在表单加载后发生一次,或者,如果您希望每次表单获得焦点时发生,请使用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;
}