65.9K
CodeProject 正在变化。 阅读更多。
Home

窗体淡入淡出

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.83/5 (7投票s)

2008年9月2日

CPOL

1分钟阅读

viewsIcon

35667

downloadIcon

1359

本文将解释如何使用 VB.NET 实现窗体的淡入淡出效果。

不透明度为 100%

Fader_Test_src

淡出时

fading_form_2.png

引言

你有没有觉得你的 Windows 窗体看起来很单调,想让它们看起来更“炫酷”? 只需要几行代码,你就可以拥有一个淡入淡出的窗体。

背景

我在完成 C# 和 VB.NET 中的几个应用程序后有了这个想法。 我很容易通过 Google 找到关于淡入淡出效果的文章,并且很容易将其放入我的代码中。 然后,我的唯一 VB.NET 项目出现了,我想知道“我现在该怎么做”。 于是,我开始尝试,很快就想到了以下方法。

使用代码

这段代码使用了以下控件

  • Timer1 - 用于淡出窗体
  • Timer2 - 用于淡入窗体

首先,创建一个新项目并命名为 Fade Form(淡入淡出窗体)。 一旦生成的窗体出现,就向窗体添加两个 Timer 控件,分别命名为 Timer1Timer2。 双击 Timer1,代码编辑器将出现。 添加以下代码

'This will decrement the opacity.
Me.Opacity -= 0.06
'Now that the form is at zero opacity we must 'dispose' of the form.
If Me.Opacity = 0 Then Me.Dispose()

现在,双击 Timer2 并添加以下代码

Dim opacityFade As Single
'from minimum transparency to maximum transparency with increment .
For opacityFade = 0 To 1 Step 0.01
    Me.Opacity = opacityFade
    Me.Refresh()
'This tells the program to pause for a certain number of milliseconds.
System.Threading.Thread.Sleep(10)
Next opacityFade
Me.Opacity = 1
'Now the fade in has finished we need it to stop.
Timer2.Enabled = False

现在我们已经有了淡入淡出的函数。 剩下的就是调用它们。 为此,选择窗体,转到属性窗格,然后单击“事件”按钮。 对于 Timer1,转到“窗体关闭”事件,双击它,并添加以下内容

Timer1.Enabled = True
e.Cancel = True

对于 Timer2,转到“加载”事件,双击它,并添加以下内容

Timer2.Enabled = True

这是完整的代码

Public Class Form1

    Private Sub Timer1_Tick(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles Timer1.Tick
        Me.Opacity -= 0.06
        If Me.Opacity = 0 Then Me.Dispose()
    End Sub

    Private Sub Timer2_Tick(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles Timer2.Tick
        Dim opacityFade As Single
        For opacityFade = 0 To 1 Step 0.01
            Me.Opacity = opacityFade
            Me.Refresh()
            System.Threading.Thread.Sleep(10)
        Next opacityFade
        Me.Opacity = 1
        Timer2.Enabled = False
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As System.Object, _
                ByVal e As System.Windows.Forms.FormClosingEventArgs) _
                Handles MyBase.FormClosing
        Timer1.Enabled = True
        e.Cancel = True
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MyBase.Load
        Timer2.Enabled = True
    End Sub
End Class

现在你已经拥有了淡入淡出效果。

关注点

如果你有任何改进建议,我将非常乐意并感激地添加它们。

© . All rights reserved.