My problem is that I have a button in a winforms application that I would like to create a hover effect for. I have already achieved this effect by selecting this button, moving to the properties pane, selecting the Events, and double clicking the MouseEnter Event. This automatically creates a method in the c# code, and I can go into that method change the background color, no problem. I use a similar process for the MouseLeave Event and change the color back. This I know how to do.
Since each user control also has many buttons on it, I've been able to create generic methods (like below), and reuse these methods for each button within the user control. This is easy to select a method with the appropriate signature from the properties under events. I can find it in the dropdown next to the method. However, I have many user controls which have buttons on them, so these 2 methods are repeated in every single class.
What I've done to attempt to clean this up, is create a little static class. Then I can go into the designer (after building) and this works 100%. This not only reduces redundant code but also allows for a style change if ever the hover color needed to change, without modifying each code behind. However, if I were ever to make a modification the the user control, my reference to the method in the designer gets wiped out by the designer. The line of code just disappears.
Everything I read says "don't change the designer" for this exact reason. However, the visual studio user interface does not allow me a way to reference a method in an outside class. Any advice would be much appreciated.
private void Mouse_Enter(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.Enabled == true) btn.BackColor = Color.LightGray;
}
private void Mouse_Leave(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.Enabled == true) btn.BackColor = Color.White;
}
public static class ButtonHelper
{
public static void Mouse_Enter(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.Enabled == true) btn.BackColor = Color.LightGray;
}
public static void Mouse_Leave(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.Enabled == true) btn.BackColor = Color.White;
}
designer
this.btnEdit.UseVisualStyleBackColor = false;
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
this.btnEdit.MouseEnter += new System.EventHandler(ButtonHelper.Mouse_Enter);
this.btnEdit.MouseLeave += new System.EventHandler(this.Mouse_Leave);
.MouseXXXX +=lines out of the .designer file and to the UserControl's constructor or something. However, a better way would be to create a custom button (one that inheritsButton), then override bothOnEnterandOnLeavemethods to add your highlighting logic. That way, you don't have to handle theEnterandLeaveevents for each button individually. You could also expose properties to allow customizing the highlight color through the designer.