Opacity at 100%
On Fade Out
Introduction
Have you ever thought that your Windows forms have looked boring and wanted them to look more "cool"? Well, in just a few lines of code, you can have a form that fades in and fades out.
Background
I had the idea for this when I finished making a few applications in C# and VB.NET. I had quite easily found articles through Google about fading, and had placed it inside my code quite easily. Then, my only VB.NET project came up, and I thought "How could I do it now". Well, I set out, and soon came up with the following.
Using the code
This code uses the following controls:
Timer1
- To fade the form out
Timer2
- To fade the form in
First things first. Create a new project and call it Fade Form. Once the generated form appears, add two Timer
controls to the form called Timer1
and Timer2
. Double click Timer1
and the code editor will appear. Add the following code:
Me.Opacity -= 0.06
If Me.Opacity = 0 Then Me.Dispose()
Now, double click Timer2
and add the following code:
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
We now have the functions for the fades. All that is left to do is call them up. To do this, select the form and go to the Properties pane and click the Events button. For Timer1
, go to the "Form Closing" event, double click it, and add this:
Timer1.Enabled = True
e.Cancel = True
For Timer2
, go to the "Load" event, double click it, and add this:
Timer2.Enabled = True
Here is the whole code:
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
You now have a fade in and fade out effect.
Points of Interest
If you have any ideas for improvement, I would be more than happy and grateful to add them.