The NewForm did not close itself when every time i called a "New Form", but the Main Form does

Hi everyone, i have a problem. I already can closed the MainForm when i called the FirstForm, but when i called a "NewForm" again in the FirstForm, it called the SecondForm, but the FirstForm did not closed, so i have a 2 forms on my taskbar.

How do i fix that?

Here is the code:

private void AddNewForm(object sender, EventArgs e)
        {
            Form newForm = new Form();

            AddObjects(sender, e, newForm);

            UpdateTextPosition(sender, e);

            newForm.Size = new Size(1360, 735);

            newForm.Text = "Selling System";

            newForm.FormBorderStyle = FormBorderStyle.Fixed3D;

            newForm.AutoScaleMode = AutoScaleMode.Font;

            newForm.AutoScroll = true;

            newForm.AutoSizeMode = AutoSizeMode.GrowAndShrink;

            newForm.StartPosition = FormStartPosition.Manual;

            newForm.Location = new Point(0, 0);

            newForm.MaximizeBox = false;

            newForm.Controls.Add(label1);

            newForm.Controls.Add(label2);

            newForm.Controls.Add(label3);

            newForm.Controls.Add(label4);

            newForm.Controls.Add(label5);

            newForm.Controls.Add(label6);

            newForm.Controls.Add(label7);

            newForm.Controls.Add(menuStrip1);

            CloseForm(sender, e);

            newForm.ShowDialog();
        }

        private void CloseForm(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                Action act = () =>
                {
                    this.Hide();
                };

                this.Invoke(act);
            }

            else
            {
                this.Hide();
            }
        }

Thanks in advance!

Try making the CloseForm method private static void. Next at the top of the Close form method put Form frm = sender as Form(); and where you have this. in the CloseForm method swop it for frm.... see if it works.

Edited 3 Years Ago by ChrisHunter

Hi ChrisHunter, thanks for replying this post. I already tried your suggestion, but it didn't work. Maybe i put the code in wrong place or i misunderstood you, anyways it didn't work. Thanks in advance!

As @ChrisHunter said, there is a language latency I hope.

As per my analysis of your code, the problem is with the following statement of your code.

if (this.InvokeRequired)
{
Action act = () =>
{
this.Hide();
};

Instead of that Hide() function use the Close() function.

Because Hide() makes the form to run at background where Close() closes the form.

Hope this helps you...

Have a happy coding...:D

This article has been dead for over six months. Start a new discussion instead.