Search code examples
c#visual-studiofunctionmouseentermouseleave

Make a function for MouseEnter and MouseLeave


I need to make a function that will show and hide a label when the mouse enter and leaves the area of a button.

I started doing it individually for each button, but as there will be more than 5 the code became repetitive so it is necessary to make a function. I just started in c# so I am a bit lost.

It looks like this for each button:

private void BtnP1_MouseEnter(object sender, EventArgs e)
        {
            LblP1.Visible = true;
        }
private void BtnP1_MouseLeave(object sender, EventArgs e)
        {
            LblP1.Visible = false;
        }

the label its set to visible = false so when the mouse enter the button it will show the label linked and will hide when it leaves.

Please look this as reference: https://youtu.be/qf5R1PI3l6k


Solution

  • What Jim said is right, I will add an example code for you here:

    Assuming your buttons and labels are both named button1,button2... label1,label2...:

    Make the event get the specific name from the sender:

    private void BMouseMouseEnter(object sender, EventArgs e)
    {
        Button? button = sender as Button;
        string buttonName = button.Name;
        int index = int.Parse(buttonName.Substring("button".Length));
        Label? label = this.Controls.Find("label" + index.ToString(), true).FirstOrDefault() as Label;
        label.Visible = true;
    
    }
    private void BMouseMouseLeave(object sender, EventArgs e)
    {
        Button? button = sender as Button;
        string buttonName = button.Name;
        int index = int.Parse(buttonName.Substring("button".Length));
        Label? label = this.Controls.Find("label" + index.ToString(), true).FirstOrDefault() as Label;
        label.Visible = false;
    }
    

    You can add corresponding events to each button in the load or definition. It adds events to them by finding all the buttons of the form. Of course, you need to pay attention to that if there are other events on the form that should not have such events buttons require additional consideration.

    foreach (Control control in this.Controls)
    {
        if (control is Button)
        {
            control.MouseEnter += new EventHandler(BMouseMouseEnter);
            control.MouseLeave += new EventHandler(BMouseMouseLeave);
        }
    }
    

    You can also manually swipe selection events for each button's corresponding event.

    enter image description here

    enter image description here