You should wire-up a single MouseEnter
and MouseLeave
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's MouseEnter
and MouseLeave
events' drop-down lists.
The code would then need to check which button from which the event was fired, as follows:
private void btnWithHoverBorder_MouseEnter(object sender, EventArgs e)
{
Button eventButton = (Button) sender;
oldColor = eventButton.FlatAppearance.BorderColor;
eventButton.FlatAppearance.BorderColor = mouseOverColor;
}
private void btnWithHoverBorder_MouseLeave(object sender, EventArgs e)
{
Button eventButton = (Button) sender;
eventButton.FlatAppearance.BorderColor = oldColor;
}
I presume oldColor
is a global? This might get out of sync if something "odd" happens where your MouseEnter
event is fired for another button, before the corresponding MouseLeave
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:
private void btnWithHoverBorder_MouseEnter(object sender, EventArgs e)
{
Button eventButton = (Button) sender;
eventButton.tag = eventButton.FlatAppearance.BorderColor;
eventButton.FlatAppearance.BorderColor = mouseOverColor;
}
private void btnWithHoverBorder_MouseLeave(object sender, EventArgs e)
{
Button eventButton = (Button) sender;
eventButton.FlatAppearance.BorderColor = (Color)eventButton.tag;
}
(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 an Object
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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…