Thursday, October 8, 2009

Automatically fading buttons in VB.NET

I often find myself obsessing over the finer parts of interface design with my applications. I always thought buttons that innocuously faded from their mouseover color back to their default background color was something really nice and not *too* flashy. Since I couldn't find any material for replicating this in VB.NET I did what all programmers do, I wrote one myself. I hope this code helps anyone attempting to do something similar. Improve upon it if you wish, I am just posting the basic code, it will works best if you encapsulate it in a UserControl...

Public Class Form1
Friend WithEvents btnTimer As New Timer
Dim RedValue As Integer
Dim GreenValue As Integer
Dim BlueValue As Integer
Dim RAdd As Integer = 0
Dim Gadd As Integer = 0
Dim Badd As Integer = 0
Dim MyBackColor As Color



Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

btnTimer.Stop()
MyBackColor = Button1.BackColor
End Sub

Private Sub Button1_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.MouseLeave

RedValue = CInt(MyBackColor.R) - CInt(Button1.FlatAppearance.MouseOverBackColor.R)
GreenValue = CInt(MyBackColor.G) - CInt(Button1.FlatAppearance.MouseOverBackColor.G)
BlueValue = CInt(MyBackColor.B) - CInt(Button1.FlatAppearance.MouseOverBackColor.B)
RAdd = 0
Gadd = 0
Badd = 0
btnTimer.Interval = 1
btnTimer.Start()



End Sub

Private Sub btnTimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTimer.Tick
Select Case RedValue
Case Is <>
RAdd = RAdd - 1
RedValue = RedValue + 1
Case Is > 0
RAdd = RAdd + 1
RedValue = RedValue - 1
Case Is = 0
RAdd = RAdd + 0
End Select
Select Case GreenValue
Case Is <>
Gadd = Gadd - 1
GreenValue = GreenValue + 1
Case Is > 0
Gadd = Gadd + 1
GreenValue = GreenValue - 1
Case Is = 0
Gadd = Gadd + 0
End Select
Select Case BlueValue
Case Is <>
Badd = Badd - 1
BlueValue = BlueValue + 1
Case Is > 0
Badd = Badd + 1
BlueValue = BlueValue - 1
Case Is = 0
Badd = Badd + 0
End Select
Button1.BackColor = Color.FromArgb(CInt(Button1.FlatAppearance.MouseOverBackColor.R) + RAdd, CInt(Button1.FlatAppearance.MouseOverBackColor.G) + Gadd, CInt(Button1.FlatAppearance.MouseOverBackColor.B) + Badd)
If BlueValue = 0 And RedValue = 0 And GreenValue = 0 Then
btnTimer.Stop()

End If