Fade the form in on MouseEnter and Fade out on MouseLeave
This snippet teaches the bearer how to fade his/her forms in or out according to the focus in the window. The snippet was based on the effects Paint .NET currently uses. It requires a timer, a global variable and two events to function.
[VB.NET]
Private Const fadeSpeed As Integer = 10 ' Controls the fade speed (Milliseconds for every change of opacity)
Dim WithEvents tmrFade As New Timer() ' Our timer control.
Dim fadeDirection As Boolean = False ' Boolean value of whether we want to fade up or down.
''' <summary>
''' Timer used to fade the form.
''' </summary>
''' <remarks>
''' fadeDirection is used to determine whether the timer should be incrementing or decrementing
''' the Opacity of the Form.
''' </remarks>
Private Sub tmrFade_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmrFade.Tick
If fadeDirection Then ' If we are incrementing the opacity
If Me.Opacity <= 1.0 Then ' If the opacity is less than 100%
Me.Opacity += 0.01 ' Increment Opacity by 1%
Exit Sub ' Exit the Subroutine to avoid Disabling the Timer.
End If
Else ' If we are decrementing the opacity
If Me.Opacity >= 0.5 Then ' If the opacity is more than 50%
Me.Opacity -= 0.01 ' Decrement Opacity by 1%
Exit Sub ' Exit the Subroutine to avoid Disabling the Timer.
End If
End If
' Disable the timer as it doesn't fit into any of the conditions above.
tmrFade.Enabled = False
End Sub
Private Sub Form1_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.MouseEnter
' Tell the timer, that we want to fade up.
fadeDirection = True
' Initialise the timer.
tmrFade.Interval = fadeSpeed
tmrFade.Enabled = True
End Sub
Private Sub Form1_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.MouseLeave
' Tell the timer, that we want to fade down.
fadeDirection = False
' Initialise the timer
tmrFade.Interval = fadeSpeed
tmrFade.Enabled = True
End Sub
See Also
Dream In Code Submission - http://www.dreamincode.net/code/snippet1422.htm
page revision: 0, last edited: 19 Nov 2007 09:17