Come back to home page

Fading Visual Effect (Form; VB.NET)Download

In VB.NET, the fading effect on form can be easily programmed using the 'Opacity' property of form. In this tutorial we will discuss the use of this property. Looks very basic? Yes, it is. However, it will surely help beginners and moreover, I have used some stuff like Optional parameters and use of threads (simple use of CurrentThread to pause the application) in the code. This might be of some interest to some of our friends.

The Code

Private Sub btnFadeIt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnFadeIt.Click
    FadeOut(Me , 0.001)
    FadeIn(Me , 0.001)
End Sub

Above piece of code is used to call the public functions - FadeOut and FadeIn.

Public Sub FadeOut(ByVal iForm As Form, Optional ByVal speed As Double = 0.01, _
Optional ByVal disposeForm As Boolean = False )
    Dim i As Double
    For i = 1 To 0 Step -speed
       
iForm.Opacity = i
    Next
    If disposeForm = True Then  iForm.Dispose()
End Sub

The function written above is pretty simple, it decreases the Opacity of the form passed at the specified rate and if the disposeForm argument is true, then the form is disposed.

If we declare a parameter as Optional, as in the code above, specifying the value of that parameter while calling the function becomes optional. In this case (when no value is specified), the default value, specified in the method signature, is used. For more details, download the source code from the the link given below and experiment with it (a few examples are also given there).

Public Sub FadeIn(ByVal iForm As Form, Optional ByVal speed As Double = 0.01, _
Optional ByVal disposeForm As Boolean = False, Optional ByVal delay As Double = 0)
    Dim i As Double
    For i = 0 To 1 Step speed
        iForm.Opacity = i
    Next
    If disposeForm = True Then
        Threading.Thread.CurrentThread.Sleep(delay)
        iForm.Dispose()
    End If
End Sub

In the above code, we can see a new line of code:

Threading.Thread.CurrentThread.Sleep(delay)

The CurrentThread property allows us to access the current application thread and Sleep method pauses the application for the specified time in milliseconds (1 second = 1000 milliseconds).

Did this tutorial help you in any way? Please send your comments at rahul@coder000.com. This gives motivation for better and continuous efforts.