Home > Blockchain >  Control events trigger on other forms than my intended formC#
Control events trigger on other forms than my intended formC#

Time:01-07

I got a question about creating new forms in C#. I want to create multiple forms (MainPanel) as shown in the code below. This creates a new form and displays it.

        private void Panel_MouseClick(object sender, MouseEventArgs e)
        {
            Form mp = new MainPanel();
            mp.Show();
        }

In the MainPanel form I have some events and controls set up. One of the is an exit button, if you press it, it closes the form

    public partial class MainPanel : Form
    {
        private static MainPanel mainPanel;
        public MainPanel()
        {
            InitializeComponent();
            mainPanel = this;

            Panel panel = new Panel();
            panel.Name = "ExitButton";
            panel.BackColor = ExitButtonColor;
            panel.BorderStyle = BorderStyle.None;
            panel.BackColor = Color.Transparent;
            panel.Width = 30;
            panel.Height = 30;

            panel.MouseClick  = PanelExit_MouseClick;
            this.Controls.Add(panel);
        }

        private static void PanelExit_MouseClick(object sender, MouseEventArgs e)
        {
            mainPanel.Close();
        }
}

When I call for Form mp = new MainPanel(); and .Show() it, it works like intended and opens. The exit button works too. How ever, when I open a second one by creating a new new MainPanel(); and then .Show(); it. Then the exit button does not really work.

That means I have 2 open MainPanel forms, both have their own exit button. If I click on the first form exit button, clicking it will close the second form. Clicking on the exit button on the second form will also close the second form. In other words, all the events on my first form are being fired and executed on my second form.

Any idea why that happens or how to avoid it?

CodePudding user response:

It is not obvious why you used static, but that's what happens when you do. As-is, you must not allow a second instance to be created

As Hans comment under my post, I kept all my variables and methods static, keeping it the same for all created forms. Removing the static from the methods and variables did the job.

Thank you

CodePudding user response:

Side note, you don't need "mainPanel" at all though. Why store a reference to this? Just use it directly...

Change:

private static void PanelExit_MouseClick(object sender, MouseEventArgs e)
{
    mainPanel.Close();
}

To:

private void PanelExit_MouseClick(object sender, MouseEventArgs e)
{
    this.Close();
}

Removing static from the method signature as well.

  •  Tags:  
  • Related