Search code examples
c#dynamicpanelflowlayoutpanel

C# Dynamic Panel SubPanel-Event Loop bug


I am currently making an UI using a flow layout panel in visual studio 19. If i press a button it clones a panel using

public static T Clone<T>(this T controlToClone) where T : Control
    {
        PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        T instance = Activator.CreateInstance<T>();
        foreach (PropertyInfo propInfo in controlProperties)
        {
            if (propInfo.CanWrite)
            {
                if (propInfo.Name != "WindowTarget")
                    propInfo.SetValue(instance, propInfo.GetValue(controlToClone, null), null);
            }
        }

        return instance;
    }

In the same press event it fires AddNewPanel("name");

private void AddPanel(string name)
        {
            var label = new Label();
            label.AutoSize = false;
            label.TextAlign = ContentAlignment.MiddleCenter;
            label.Dock = DockStyle.Fill;
            label.Text = name;
            label.MouseEnter += labelEnter;
            label.MouseLeave += labelLeave;

            var panel = panel1.Clone();
            var button = button1.Clone();
            button.Name = "button" + new Random().Next(1, 100);

            panel.Controls.Add(button);
            panel.Controls.Add(label);

            flowLayoutPanel1.Controls.Add(panel);
        }

the event labelEnter triggers ShowButtons()

private void showButtons()
        {
            foreach (Control item in flowLayoutPanel1.Controls)
            {
                var button = item.Controls[1];
                button.Visible = true;
            }
        }

and the mouseLeave event does the same except turning Visible to false.

Now I have experienced, dynamically adding Controls to a panel which then gets added to a flowlayout panel causes some Issues. For example, the labelMouseEnter/Leave event gets looped when moving the mouse over the button. Anyone experienced this before or similiar posts regarding this? It doesn't happen when the button is initially Visible, meaning Visible is turned to true in designer View. It clones it with the visible attribute.


Solution

  • The Solution is to add a check in the MouseLeave event as following:

     private void control_MouseLeave(object sender, EventArgs e)
            {
                var control = sender as Control;
                if (control.ClientRectangle.Contains(control.PointToClient(Cursor.Position))) return;
                //rest 
                ShowButtons();
            }