Changing Buttons' Color

Tyecom

Well-known member
Joined
Aug 8, 2007
Messages
78
Programming Experience
Beginner
I have a Windows Form that has several buttons on it. I would like the buttons background color to change when clicked/selected. Do anyone know how to do this? Thanks in advance. I'm using VB.Net 2005.
 
Use this code:
VB.NET:
    Private Sub Buttons_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 
        Dim btn As Button = sender
        btn.BackColor = Color.Red
    End Sub

    Private Sub Buttons_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 
        Dim btn As Button = sender
        btn.BackColor = SystemColors.Control
    End Sub
After you've add the code go to design view and select all buttons, then in properties window set view to display events, find MouseUp and select the Buttons_MouseUp handler, same with MouseDown.

You can do similar for when button is selected (active, but not clicked) by using the Enter/Leave events.

If you have different colors and use hi-lighting both for selection and click, instead of hardcoding the color to return to, you can use a class level Color variable where you store the previous value and set back to this instead of for example SystemColors.Control.
 
Back
Top