In my Windows forms application written in C# I have a bunch of buttons. When the user's mouse hovers over a button, I want the button's border to change.
Currently I have multiple instances of the following (a copy for each button):
private void btnStopServer_MouseEnter(object sender, EventArgs e)
{
oldColor = btnStopServer.FlatAppearance.BorderColor;
btnStopServer.FlatAppearance.BorderColor = mouseOverColor;
}
private void btnStopServer_MouseLeave(object sender, EventArgs e)
{
btnStopServer.FlatAppearance.BorderColor = oldColor;
}
Since I have a lot of buttons, the code to change the color of the button's border takes up a lot of space.
Is there any simpler way that I could do this?
You should wire-up a single
MouseEnter
andMouseLeave
to each control that needs this functionality (rather than writing a new version of each method for each control). Assuming you're using Visual Studio, this can be done by changing the target method name for the event, in each Button's property pane. If you write the following code first, then this method will appear in the property'sMouseEnter
andMouseLeave
events' drop-down lists.The code would then need to check which button from which the event was fired, as follows:
I presume
oldColor
is a global? This might get out of sync if something "odd" happens where yourMouseEnter
event is fired for another button, before the correspondingMouseLeave
is caught. To make this more robust, I'd consider storing the old color on the Button's.tag
property, so that it's self-contained.Eg:
(The tag is basically a hook on which to tag "anything" relevant to a specific instance of a control, that there is not already a property for. It's of type
Object
which means you can tag anything there, but when you read from it, you need to cast it back to whatever type you put there in the first place. But because it's anObject
you can put anything there, including eg a custom class that contains multiple properties, or an array, etc if you need to tag a control with more than one thing).